clavia-auth / authzen
An OpenID AuthZEN 1.0 client on PSR-18 and a PSR-15 middleware that enforces its decisions
Requires
- php: ~8.3.0 || ~8.4.0 || ~8.5.0
- fig/http-message-util: ^1.1
- psr/clock: ^1.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.1
- psr/http-message: ^1.1 || ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- psr/log: ^2.0 || ^3.0
- psr/simple-cache: ^2.0 || ^3.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.9
- nyholm/psr7: ^1.8.2
- phpunit/phpunit: ^12.4
- psalm/plugin-phpunit: ^0.22.2
- squizlabs/php_codesniffer: ^4.0
- vimeo/psalm: ^6.13
Suggests
- guzzlehttp/guzzle: A PSR-18 client, with a timeout of its own (README: Fail closed)
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-29 18:10:14 UTC
README
An OpenID AuthZEN 1.0 client on PSR-18, and a
PSR-15 middleware that enforces its decisions. Your API asks a policy decision point, at request time,
whether the caller may do what it asks, and refuses anything but a true:
| The decision point says | Your API answers |
|---|---|
{"decision": true} |
your handler runs |
{"decision": false} |
403, your handler never runs |
| nothing usable: unreachable, too slow, failing, refusing the request, answering nonsense | 503, never a pass-through |
It works with any AuthZEN decision point. With Clavia, the decisions come from OpenFGA, behind Clavia's Authorization API, and the client obtains and caches its own access token.
Install
composer require clavia-auth/authzen
Until 0.1.0 the package was clavia/authzen, now abandoned: require clavia-auth/authzen instead (the
namespace is the same).
PHP 8.3 or later. Bring a PSR-18 client and PSR-17 factories (Guzzle has both), and a PSR-16 cache for the token and the metadata.
Protect a route
use Clavia\AuthZen\Credentials\ClientCredentials; use Clavia\AuthZen\HttpAuthZenClient; use Clavia\AuthZen\Middleware\{AttributeResource, AuthZenMiddleware, MethodAction, ProblemResponder, TokenSubject}; use Fig\Http\Message\RequestMethodInterface as Method; use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; $http = new Client(['timeout' => 2, 'allow_redirects' => false, 'http_errors' => false]); $psr17 = new HttpFactory(); $authzen = HttpAuthZenClient::discover('https://management.example.com', $http, $psr17, new ClientCredentials( 'https://auth.example.com/oauth2/token', $clientId, $clientSecret, $http, $psr17, $psr17, cache: $cache, audience: 'https://management.example.com/access', scope: 'evaluate:access', ), $cache); $app->get('/documents/{id}', $showDocument)->add(new AuthZenMiddleware( $authzen, new ProblemResponder($psr17, $psr17), subject: TokenSubject::fromClaims('token_claims'), action: MethodAction::map([ Method::METHOD_GET => 'viewer', Method::METHOD_PUT => 'editor', Method::METHOD_DELETE => 'owner', ]), resource: new AttributeResource('document', 'id'), ));
For GET /documents/q3-report, by a person whose validated token says "sub": "3f8e…", the decision
point is asked:
{
"subject": {"type": "user", "id": "3f8e…"},
"action": {"name": "viewer"},
"resource": {"type": "document", "id": "q3-report"}
}
Put the middleware after your authentication (which validates the token and leaves its claims in
the token_claims attribute) and after routing (which leaves the route's id).
Who, what, on what
The middleware takes three resolvers, and a fourth for the context, each a class or a closure
fn (ServerRequestInterface $request): …:
| Parameter | Gives | Provided |
|---|---|---|
subject |
a Subject |
TokenSubject::fromClaims($attribute): the token's sub as a user, or, for an application acting for itself (no sub, or a sub equal to its client_id, RFC 9068 §2.2), its client_id as a client. TokenSubject::fromAttributes() reads league/oauth2-server's attributes. |
action |
an Action |
Action::named('viewer') for a route with one action; MethodAction::map([...]) by HTTP method |
resource |
a Resource |
new AttributeResource($type, $attribute): a route parameter as the identifier |
context |
an array | none by default: what your policies read beyond the three (the time, the network) |
A resolver that cannot answer throws Unresolvable: the request is refused (403) and the decision
point is not asked. A method MethodAction does not map, a request without a subject, a route without
its parameter: all refused.
On a permit, your handler finds the decision in the request attribute Clavia\AuthZen\Decision, its
context holding whatever the decision point added (obligations, hints).
The refusals
ProblemResponder answers RFC 9457 problem documents, never cached, that say nothing of the
decision's context or of the failure. Implement Responder to answer otherwise; keep 403 and 503.
Every failure is logged (pass a PSR-3 logger as logger:), by kind and status, never with a token.
Fail closed
There is no decision without the decision point's answer, and the middleware never invents one. What you configure decides how fast "no answer" comes:
- Give the PSR-18 client a timeout. PSR-18 has none of its own: without one, a decision point that hangs holds your request as long as PHP lets it. Two seconds is Clavia's own budget for OpenFGA.
- Follow no redirects. An answer comes from the endpoint the metadata names, or it is no answer.
- Treat
503as a denial in whatever calls your API: retry later, never assume.
Any AuthZEN decision point
discover() reads the decision point's metadata from /.well-known/authzen-configuration (AuthZEN
§9) the first time it is needed, checks that it names the decision point it was fetched from, and
keeps it in the cache for an hour. An API the metadata does not name is not offered (§9.1.1): asking
for it throws UnsupportedOperation, which the middleware answers 503.
A decision point that publishes no metadata has every API at its default path:
use Clavia\AuthZen\Credentials\StaticCredentials; use Clavia\AuthZen\Metadata; $authzen = new HttpAuthZenClient( Metadata::defaults('https://pdp.example.com'), $http, $psr17, $psr17, StaticCredentials::header($apiKey), );
Credentials are ClientCredentials (an OAuth 2.0 token by the client credentials grant, RFC 6749
§4.4), StaticCredentials::bearer($token) or ::header($value), or NoCredentials. A 401 from the
decision point renews the credentials and asks once more.
With Clavia
What the operator sets up is in Clavia's
fine-grained authorization guide:
a model for your API, your API's machine client named as the one that speaks for it, and its grant on
the Authorization API (evaluate:access, and search:access to search). Then:
- the decision point is
https://management.{domain}, the token endpointhttps://auth.{domain}/oauth2/token, the audiencehttps://management.{domain}/access; - subjects are
user(thesubof people's tokens) andclient(a client identifier), and actions are the relations of your model; - Clavia adds what it knows of the subject to the context, and refuses a
context.claviaof yours.
The client on its own
The middleware asks one question per request. Ask more, or search, with the client:
use Clavia\AuthZen\{Action, Evaluation, Evaluations, EvaluationsSemantic, PartialEvaluation, Resource, Subject}; use Clavia\AuthZen\Search\{Page, ResourceSearch}; $ada = Subject::of('user', '3f8e2d1c-5b4a-4c9e-8d7f-6a5b4c3d2e1f'); $report = Resource::of('document', 'q3-report'); $authzen->evaluate(Evaluation::of($ada, Action::named('viewer'), $report))->isPermitted(); // Several questions, sharing defaults (§7), up to and including the first denial. $decisions = $authzen->evaluations(Evaluations::sharing( [PartialEvaluation::of(action: Action::named('viewer')), PartialEvaluation::of(action: Action::named('editor'))], subject: $ada, resource: $report, semantic: EvaluationsSemantic::DenyOnFirstDeny, )); $decisions->allPermitted(); // What may Ada view? One page at a time (§8.2). $search = ResourceSearch::of($ada, Action::named('viewer'), 'document', page: Page::of(50)); do { $page = $authzen->searchResources($search); foreach ($page->results as $document) { /* … */ } } while ($search = $search->after($page));
searchSubjects() and searchActions() work the same way. A search says what would be permitted; it
is not a decision. Enforce with an evaluation.
Every method gives the decision point's answer or throws an AuthZenException:
| Exception | When |
|---|---|
DecisionPointUnavailable |
no connection, a timeout, a 5xx, a redirect, a malformed answer, metadata for another decision point, an X-Request-ID that is not the one sent |
TokenUnavailable (a DecisionPointUnavailable) |
the token endpoint refused the client, or could not be reached |
RequestRejected |
a 4xx: a question the decision point cannot ask, credentials it does not take (after a renewal). detail() holds its words, for your logs |
UnsupportedOperation |
the decision point does not offer that API |
InvalidValue |
a value the information model cannot hold |
Caching
The cache holds two things: the metadata document (an hour), and the access token, until thirty seconds before it expires, so that every PHP process of your API shares one. The token is a secret: give a cache that only your API can read. Nothing else is cached: decisions never are.
Development
composer install
composer check # PHPCS (PSR-12), Psalm level 1, PHPUnit
The tests play the AuthZEN working group's recorded Todo interoperability scenario
(test/Interop/fixtures), and run against a real Clavia and a live interoperability decision point
when told where they are: see CONTRIBUTING.md.
Specifications
AuthZEN Authorization API 1.0 · RFC 6749 (OAuth 2.0) · RFC 6750 (bearer tokens) · RFC 8707 (resource indicators) · RFC 9068 (JWT access tokens) · RFC 9457 (problem details) · PSR-7, PSR-15, PSR-16, PSR-17, PSR-18, PSR-20
License
BSD-3-Clause. See LICENSE.