Search by

clavia-auth / clavia-php

phayne

The Clavia SDK for PHP: access token checks for APIs, sign-in for applications and a Management API client, on PSR-7, PSR-15, PSR-17 and PSR-18

v0.2.0 2026-11-30 01:14 UTC

This package is auto-updated.

Last update: 2026-11-30 01:15:28 UTC


README

The Clavia SDK for PHP: access token checks for APIs, sign-in for server-rendered applications, and a Management API client, framework-free on PSR-7, PSR-15, PSR-17 and PSR-18.

It speaks standards only (OpenID Connect, RFC 9068, RFC 9449, RFC 7662, RFC 9470, RFC 9728), configures itself from the issuer's discovery document, and holds Clavia's security rules on the client side.

0.2.0: access token checks for an API (Clavia\Sdk\Api), sign-in for applications (Clavia\Sdk\Application) and the Management API client (Clavia\Sdk\Management). The design is docs/design/sdks.md in clavia; what each release holds is in CHANGELOG.md.

Requirements

  • PHP 8.4 or later.
  • Clavia 0.6.1 or later: the oldest release it is tested against, end to end, beside Clavia's edge (test/E2e). It speaks standards only, so any conformant server should do.
  • A PSR-7 and PSR-17 implementation and a PSR-18 client of your choice. The client must follow no redirect: the SDK treats a 3xx from the issuer as a failure (Guzzle's sendRequest() follows none; Symfony's Psr18Client needs max_redirects: 0).
  • A PSR-16 cache shared by your processes (Redis, APCu) is recommended: without one, each process fetches the issuer's discovery document and keys for itself.

Installation

composer require clavia-auth/clavia-php:^0.2

Before 1.0, a minor version may carry breaking changes (the changelog says what to do), so require a minor range.

The issuer

Everything starts from the issuer: one URL, from which the SDK reads its discovery document and its keys.

use Clavia\Sdk\Discovery;
use Clavia\Sdk\Environment;
use Clavia\Sdk\Issuer;
use Clavia\Sdk\IssuerUnavailable;

$issuer = Issuer::fromEnvironment();                     // CLAVIA_ISSUER, https
// $issuer = Issuer::fromUrl('http://localhost:8080', Environment::Development);

$discovery = new Discovery($issuer, $httpClient, $psr17Factory, $psr17Factory, cache: $cache, logger: $logger);

try {
    $document = $discovery->document();                  // kept for its max-age, at most a day
    $key = $discovery->keys()->key($kid);                // a public signing key, or null
    $only = $discovery->keys()->onlyKeyFor('RS256');     // the set's one key for RS256, or null: none or several
} catch (IssuerUnavailable $error) {
    // $error->endpoint, $error->problem, $error->status; logged already, never with the body
}

The document's issuer must equal the configured one exactly. An unknown kid fetches the keys again at most once a minute. onlyKeyFor() is for a token that names no key, which OpenID Connect Core §10.1 allows when only one key could be meant: the one key whose own algorithm is the token's. The SDK takes it for an ID token or a logout token, never for an access token. Every error the SDK raises on purpose implements Clavia\Sdk\ClaviaError, whose kind() is one case of Clavia\Sdk\ErrorKind.

An API

Clavia\Sdk\Api\RequireAccessToken is a PSR-15 middleware that lets a request through only with an access token good for this API and for what the route requires. The token reaches the handler as a request attribute.

use Clavia\Sdk\Api\AccessToken;
use Clavia\Sdk\Api\Introspection;
use Clavia\Sdk\Api\ProtectedResourceMetadata;
use Clavia\Sdk\Api\RequireAccessToken;
use Clavia\Sdk\Api\Requirements;
use Clavia\Sdk\Api\Verifier;
use Clavia\Sdk\Redis\RedisReplayCache;

$verifier = new Verifier(
    $discovery,
    audience: 'https://reports.example.com',       // the API's identifier at Clavia
    url: 'https://reports.example.com',            // its public URL: what a DPoP proof must name
    replayCache: new RedisReplayCache($redis),     // each DPoP proof accepted once, across processes
    introspection: Introspection::asClient('reports-api', $secret),   // for opaque tokens; optional
);

$readReports = new RequireAccessToken($verifier, Requirements::scopes('read:reports'), $psr17Factory, $psr17Factory);
$exportReports = new RequireAccessToken(
    $verifier,
    Requirements::scopes('export:reports')->withAcr('urn:clavia:mfa'),
    $psr17Factory,
    $psr17Factory,
);

// in a handler behind it
$token = $request->getAttribute(AccessToken::class);   // $token->sub, $token->scopes, $token->claims

// at /.well-known/oauth-protected-resource (RFC 9728)
$metadata = new ProtectedResourceMetadata($verifier, ['read:reports', 'export:reports'], $psr17Factory, $psr17Factory);

A token is read from the Authorization header only, as Bearer or DPoP. A token bound to a key (cnf.jkt) needs DPoP and a proof in exactly one DPoP header, checked as Clavia checks its own (RFC 9449 §4.3, §7): ES256, EdDSA or RS256; the request's method; the API's configured URL with the request's path, never the Host header; made at most a minute ago; the token's hash; the key the token is bound to; and its jti once, in the replay cache. RedisReplayCache needs ext-redis; InMemoryReplayCache::forDevelopment() is for a single development process. An application's own cache passes Clavia\Sdk\Testing\ReplayCacheContract.

A JWT is verified with the issuer's key and that key's own algorithm, never the one its header names; its issuer, its audience (before any scope) and its expiry are checked. Any other token goes to the issuer's introspection endpoint, and the answer is kept only when you ask (cachedFor(), at most a minute). A refusal answers with its status and its WWW-Authenticate challenge: insufficient_scope (403) names the scopes, and insufficient_user_authentication (401, RFC 9470) names the acr_values or max_age the client must come back with. A client acting as itself (its sub is its client_id, $token->machine) has no person to step up: a level and a recent sign-in don't apply to it, and its scopes still do. Outside the middleware, $verifier->verify($request, $requirements) returns the AccessToken or throws a TokenRefused, whose response() is the answer to send.

examples/api is a whole API on it in one file, which the end-to-end tests drive against Clavia's stack.

Signing people in

Clavia\Sdk\Application signs people in to a server-rendered application: the authorization code flow with PKCE, pushed authorization requests when the issuer offers them, the session kept on the server with its refresh serialised across processes, sign-out at Clavia, back-channel logout and step-up. The browser holds only a random handle in a cookie; the tokens never reach it.

use Clavia\Sdk\Application\Authentication;
use Clavia\Sdk\Application\CurrentSession;
use Clavia\Sdk\Application\RequireSession;
use Clavia\Sdk\Application\Routes;
use Clavia\Sdk\Application\Settings;
use Clavia\Sdk\Application\StepUpRequired;
use Clavia\Sdk\Discovery;
use Clavia\Sdk\Redis\RedisAttemptStore;
use Clavia\Sdk\Redis\RedisReplayCache;
use Clavia\Sdk\Redis\RedisSessionStore;

// CLAVIA_ISSUER, CLAVIA_CLIENT_ID, CLAVIA_CLIENT_SECRET, CLAVIA_APP_URL (the application's origin) and
// CLAVIA_SESSION_KEY (SessionKeys::generate(); several, separated by commas, rotate them)
$settings = Settings::fromEnvironment()->withAudience('https://reports.example.com');
$discovery = new Discovery($settings->issuer, $httpClient, $psr17Factory, $psr17Factory, cache: $cache);

$authentication = new Authentication(
    $settings,
    $discovery,
    new RedisSessionStore($redis),     // sessions, shared by every process
    new RedisAttemptStore($redis),     // sign-ins under way
    new RedisReplayCache($redis),      // each back-channel logout token accepted once
    $psr17Factory,
    $psr17Factory,
);

// /auth/sign-in, /auth/callback, POST /auth/sign-out, /auth/backchannel-logout: a PSR-15 handler
$routes = new Routes($authentication);

// in a handler
$session = $authentication->session($request);           // ?CurrentSession: $session->person->sub, ->name, ->email
$token = $authentication->accessToken($request);          // ?string, refreshed first when it is due

// calling an API with the session's token: Bearer, or DPoP with a proof (Settings::withDpop())
try {
    $response = $authentication->send(
        $request,
        $psr17Factory->createRequest('GET', 'https://reports.example.com/exports'),
    );
} catch (StepUpRequired $stepUp) {
    // the API asks for a stronger sign-in (RFC 9470): send the person to sign in again at that level
    $location = $stepUp->signInPath('/exports', $settings->base);
}

// a route only for someone signed in; anyone else is sent to sign in, and back
$requireSession = new RequireSession($authentication, $psr17Factory);
$session = $request->getAttribute(RequireSession::ATTRIBUTE);   // CurrentSession, behind it

Sign-out is a form, never a link: <form method="post" action="/auth/sign-out"><button>Sign out</button></form>. A request from another origin is refused; the session ends here first, then its refresh token is revoked, and the browser goes to Clavia to end the session there too. Register {appUrl}/auth/callback as the client's redirect URI, {appUrl}/ as its post-logout redirect URI, and https://{host}/auth/backchannel-logout as its back-channel logout URI. ID tokens and back-channel logout tokens are held to the algorithm the client is registered with, RS256 by default as Clavia signs: Settings::withIdTokenSigningAlgorithm('ES256') for a client registered otherwise. The Redis stores need ext-redis and Redis 7.0 or later; an application's own stores pass Clavia\Sdk\Testing\SessionStoreContract and AttemptStoreContract.

examples/app is a whole application on it in one file, which the end-to-end tests drive against Clavia's stack: its README has the steps that get it running against a Clavia.

The other SDKs

@clavia-auth/core, @clavia-auth/next and @clavia-auth/effect for JavaScript, and clavia-auth/authzen for AuthZEN decisions in PHP.

Contributing and security

See CONTRIBUTING.md. Report a vulnerability privately, never in a public issue: SECURITY.md.

Licence

BSD 3-Clause; see LICENSE.