Middleware
OAuth2 JWKS Middleware
Add OAuth 2 Authentication with JWKS validation to your Kipchak API.
Introduction
The Auth JWKS middleware provides a secure, automated way to verify JSON Web Tokens (JWTs) against a JSON Web Key Set (JWKS). It is designed to integrate seamlessly with OpenID Connect (OIDC) providers such as Keycloak, Auth0, or Okta.
Key features include:
- Remote Key Validation: Automatically fetches and caches public keys from a
jwksUrito verify token signatures. - Issuer, Audience and Token Type: Accepts only tokens from your issuer, issued to the clients you list, and (for Keycloak) access tokens rather than ID tokens.
- Scope Validation: Enforces access control by requiring every listed scope (e.g.,
email,profile) in the token. - CORS Support: Built-in handling for
OPTIONSpreflight requests. - Path Whitelisting: Easily exclude specific routes (like health checks) from authentication requirements.
Installation
Install the middleware via composer by running:
composer require kipchak/middleware-auth-jwks
Configuration
The configuration lives in config/kipchak.auth.jwks.php; vendor/bin/kipchak add auth-jwks copies the sample there. It defines the identity provider connection and validation rules.
Global Settings
enabled(bool): Master switch. Set totrueto enforce authentication globally.jwksUri(string): Required. The URL where your Identity Provider publishes its JSON Web Key Set.- Example:
'https://idp.example.com/realms/example/protocol/openid-connect/certs'
- Example:
issuer(string): Required. The exactissof the tokens you accept. For Keycloak:https://<host>/realms/<realm>.audience(array): Required. The client IDs whose tokens this API accepts. A token is accepted when one of them is in itsaudclaim or equals itsazpclaim. Keycloak puts the client inazp; theaudof an access token is often onlyaccount.token_type(string): Optional. When set, the token'stypclaim must equal it. Set'Bearer'for Keycloak, whose ID tokens carrytyp: IDand are otherwise signed and addressed like access tokens. Leave it out for providers with notypclaim, such as Entra ID.
The middleware throws a ConfigurationException when issuer, audience or jwksUri is missing, so a service with an incomplete configuration fails at boot.
Request Handling
ignore_options(bool): Iftrue,OPTIONSrequests (used for CORS preflight checks) are allowed through without a token.ignore_paths(array): A list of URI paths that should be publicly accessible.- Default:
['/status']
- Default:
Scope Validation
validate_scopes(bool): Iftrue, the middleware will verify that the token contains the specific scopes listed in thescopesarray.scopes(array): The scopes the token must carry. Every one is required.key_set_ttl(int, seconds, optional): How long a fetched key set is trusted before it is fetched again; 86400 when left out. SR-2026-013 requires 3600 or less, so that a key the identity provider withdraws stops being accepted within the hour. A value that is not a whole number of seconds, at least 1, fails at boot.- Default:
['email', 'profile']
- Default:
Outbound Proxy
When the API reaches the identity provider only through an outbound HTTP proxy, set the optional proxy block (version 1.43 and later). The sample configuration reads it from the environment:
'proxy' => [
'url' => env('JWKS_PROXY', env('HTTPS_PROXY', env('https_proxy', ''))), // http://host:port
'username' => env('JWKS_PROXY_USERNAME', ''),
'password' => env('JWKS_PROXY_PASSWORD', ''),
'no_proxy' => env('NO_PROXY', env('no_proxy', '')), // comma-separated hosts fetched directly
],
- An
https://jwksUriis fetched through aCONNECTtunnel, so TLS runs end to end with the identity provider and its certificate is checked as before. Anhttp://one is sent to the proxy as a full URI. urlmust behttp://host:port: PHP speaks plain HTTP to the proxy. Another scheme, such ashttps://orsocks5://, fails at boot with aConfigurationException.usernameandpassword(optional): Basic credentials for the proxy. They may also be in the URL (http://user:password@host:port, percent-encoded); the explicit keys take precedence. They are sent to the proxy only, asProxy-Authorization, and never logged: a failed fetch logs the proxy by host and port.no_proxy(string or array): Hosts fetched directly.example.comand.example.commatch that host and its subdomains,*matches every host, and a port on an entry is ignored.- An empty
url, or noproxyblock, fetches directly.
A failed fetch through the proxy, like any failed fetch, refuses the request with a 401 and is logged, and the next request tries again.
Usage
Once enabled, the middleware inspects the Authorization header of incoming requests. It expects a Bearer Token format:
Authorization: Bearer <token>
Basic Workflow
- Header Check: The middleware looks for the
Authorizationheader. If missing, the request is denied (unless the path is inignore_paths). - Signature Verification: The token's signature is validated against the public keys fetched from the
jwksUri. - Claims Check: The token must not be expired (
exp), must come fromissuer(iss), must be issued to one of theaudienceclients (audorazp), and, withtoken_typeset, must have thattyp. - Scope Check: If
validate_scopesis enabled, the token must carry every required scope.
Every token that fails steps 2 or 3 gets a 401 UNAUTHENTICATED with the message Invalid token; the reason is logged. A valid token without a required scope gets a 403 INSUFFICIENT_PRIVILEGES (RFC 6750). The key set is cached for key_set_ttl seconds, a day by default, but only when the fetch returned a valid key set: a failed fetch is not cached, so the next request tries again. A token whose kid is not in the cached set causes one new fetch, at most once a minute, so a rotated key is picked up straight away.
Using the verified token
Once a token is verified, its claims are on the request as the kipchak.auth.token attribute, a stdClass:
use Kipchak\Middleware\Auth\JWKS\Handlers\AuthJWKS;
$token = $request->getAttribute(AuthJWKS::ATTRIBUTE_TOKEN); // 'kipchak.auth.token'
$userId = $token->sub;
$clientId = $token->client_id ?? $token->azp ?? null;
Requests on ignore_paths, and preflight requests when ignore_options is on, do not carry it.
The middleware also still stores the token in the container under token, for compatibility. Prefer the attribute. In FrankenPHP worker mode the container lives for the whole worker; from 1.45 the middleware empties that entry at the start of every request, so a request that carries no token reads null from it, never the previous caller's token.
Usage Metering and Quotas read the verified claims through Consumer Identity, for example to bill each client_id or to take the plan from a plan claim. Run this middleware globally for that, so that it runs before them.
Customizing Validation per Route
While the config file sets global defaults, you can pass custom scopes when assigning the middleware to specific routes. See the implementation in the starter project, for example.
Optional sign-in
Some routes serve anonymous callers and signed-in callers alike, and do more for a caller who signs in. An MCP endpoint whose public tools sit beside tools that read one customer's data is an example. Pass optional: true for such a route (1.45 and later):
$app->any('/mcp', Mcp::endpoint('default'))
->add(new AuthJWKS($app->getContainer(), [], optional: true));
- A request with no
Authorizationheader goes through as anonymous: it carries nokipchak.auth.tokenattribute, and the container entrytokenisnull. - A request with the header is verified exactly as without the option. An expired, malformed, wrongly signed or wrongly addressed token, an empty header and another scheme are all refused with 401, and a valid token without a required scope with 403. A token that fails is never treated as anonymous.
The route itself then decides what an anonymous caller may do. The option is off by default.
Upgrading to 1.45
1.45 fixes a defect in worker mode. The container entry token kept the last verified token for the life of the worker, so a request that carried no token, took an ignored path or was refused could read the previous caller's token from it. The entry is now emptied at the start of every request. The request attribute was never affected.
An API that reads the entry only on routes behind this middleware sees no change. An API that reads it on a route without the middleware, or on an ignored path, now gets null there, which is the fix. Prefer the request attribute in new code.
1.45 also adds optional sign-in. Nothing changes for a route that does not pass it.
Upgrading to 1.43
1.43 adds the optional proxy block. Nothing changes for an API that does not set it: copy the block from the package's sample.config.php into config/kipchak.auth.jwks.php to use a proxy.
Upgrading to 1.41
1.41 fixes a security issue: earlier versions accepted any token the identity provider signed, for any of its clients, including ID tokens.
- Add
issuerandaudiencetoconfig/kipchak.auth.jwks.php, and'token_type' => 'Bearer'for Keycloak. Withoutissuerandaudience, the middleware throws at boot. - Every scope in
scopesis now required, not any one of them. Before upgrading, check in your identity provider that the tokens of each client inaudiencecarry all of them. In Keycloak,emailorprofilecan be an optional client scope, and then a token carries it only when the client asks for it. - A token that fails verification gets a 401, not a 400, with a fixed message.
Git Repository
The source code for this middleware is available on 1x.ax at https://1x.ax/mamluk/kipchak/middlewares/auth-jwks.