Authentication & Tenancy
PAM HTTP ships small, replaceable contracts for identity instead of a full auth system. An Authenticator turns a
request into a Principal; middleware stores that principal in the current request scope; AuthorizeMiddleware
checks abilities. A built-in HMAC token codec covers the common case of short-lived API access tokens.
Identity and tenant state always live in the request scope, so a persistent worker can never hand one caller’s identity to the next request.
Signed Bearer Tokens
Section titled “Signed Bearer Tokens”HmacTokenCodec issues and verifies compact HS256 tokens (JWT format) with issuer, audience, subject, a unique
jti, iat, nbf, exp and a list of abilities.
use Pam\Api\Auth\BearerTokenAuthenticator;use Pam\Api\Auth\HmacTokenCodec;use Pam\Api\Middleware\AuthenticateMiddleware;
$tokens = new HmacTokenCodec( secret: $config->string('auth.secret'), // at least 32 bytes, from a secret manager issuer: 'https://auth.example.com', audience: 'example-api',);
$app->container()->instance(HmacTokenCodec::class, $tokens);
$app->prefix('/api') ->middleware(new AuthenticateMiddleware(new BearerTokenAuthenticator($tokens), $app->container())) ->group(function (RouteRegistrar $routes): void { $routes->get('/me', [ProfileController::class, 'show']); });Issue a token after your own login flow:
$token = $tokens->issue(subject: 'user-42', abilities: ['posts.read', 'posts.write'], ttlSeconds: 900);ttlSeconds defaults to 900 and cannot exceed 86,400 (24 hours). Verification checks the signature in constant
time, the issuer and audience, and nbf and exp with a leeway of 5 seconds (configurable with
leewaySeconds, at most 300). verify() returns a TokenPrincipal or null; it never throws for a bad token.
Key Rotation
Section titled “Key Rotation”Each token carries the kid of the key that signed it (primary by default). To rotate, sign with a new key and
keep up to four retiring keys for verification:
$tokens = new HmacTokenCodec( secret: $newSecret, issuer: 'https://auth.example.com', audience: 'example-api', keyIdentifier: '2026-12', verificationKeys: ['2026-11' => $previousSecret],);Every key needs a unique identifier and at least 32 bytes. Tokens with an unknown kid are rejected before any
claim is read.
Revocation
Section titled “Revocation”Pass a TokenRevocationStore to the authenticator to reject revoked jti values:
use Pam\Api\Auth\MemoryTokenRevocationStore;
$revocations = new MemoryTokenRevocationStore();$authenticator = new BearerTokenAuthenticator($tokens, $revocations);
$revocations->revoke($principal->tokenIdentifier, expiresAt: time() + 900);The memory store is bounded (10,000 entries by default) and per worker. In a cluster, implement
TokenRevocationStore (isRevoked() and revoke()) on shared storage such as Redis.
The Authenticated Principal
Section titled “The Authenticated Principal”AuthenticateMiddleware calls the authenticator. When it returns null, the request fails with 401
(code 2). Otherwise the middleware stores the principal in the request scope as Principal and as
AuthContext, so controllers can type-hint either:
use Pam\Api\Auth\Principal;use Pam\Http\Response;
final class ProfileController{ public function show(Principal $user, Response $response): Response { return $response->json([ 'id' => $user->identifier(), 'canWrite' => $user->can('posts.write'), ]); }}Authorization
Section titled “Authorization”AuthorizeMiddleware requires an ability. It returns 403 (code 3) when there is no authenticated principal or
$principal->can($ability) is false:
use Pam\Api\Middleware\AuthorizeMiddleware;
$routes->delete('/posts/{id}', [PostController::class, 'destroy']) ->middleware(new AuthorizeMiddleware($app->container(), 'posts.delete'));For rules that depend on the resource, check in the form request’s
authorize() method or in your service, and throw an HttpException with ProblemCode::Forbidden.
Custom Authenticators
Section titled “Custom Authenticators”Any identity source works. Implement Authenticator and return your own Principal:
use Pam\Api\Auth\Authenticator;use Pam\Api\Auth\Principal;use Pam\Http\Request;
final readonly class ApiKeyAuthenticator implements Authenticator{ public function __construct(private ApiKeyRepository $keys) {}
public function authenticate(Request $request): ?Principal { $key = $request->getHeader('x-api-key');
return $key === null ? null : $this->keys->findPrincipal(hash('sha256', $key)); }}
final readonly class ApiClient implements Principal{ public function __construct(private string $id, private array $abilities) {}
public function identifier(): string { return $this->id; }
public function can(string $ability): bool { return in_array($ability, $this->abilities, true); }}Tenancy
Section titled “Tenancy”Multi-tenant APIs resolve the tenant per request. Implement TenantResolver, returning a Tenant (anything with
identifier()) or null:
use Pam\Api\Tenancy\Tenant;use Pam\Api\Tenancy\TenantResolver;use Pam\Http\Request;
final readonly class SubdomainTenantResolver implements TenantResolver{ public function __construct(private TenantRepository $tenants) {}
public function resolve(Request $request): ?Tenant { $host = $request->getHeader('host', '');
return $this->tenants->findBySlug(explode('.', $host)[0]); }}use Pam\Api\Middleware\ResolveTenantMiddleware;
$app->middleware(new ResolveTenantMiddleware( $app->container()->get(SubdomainTenantResolver::class), $app->container(), required: true,));When required is true (the default) and no tenant resolves, the request fails with 404. Otherwise the tenant
is published in the request scope as Tenant and as TenantContext for controllers and services.
Tenant-Owned Data
Section titled “Tenant-Owned Data”With the Arcano integration, protect tenant-owned roles once
during boot. Queries are then limited to the current tenant, new entities receive its key, and both fail closed
when no TenantContext exists.