SDK Toolbox docs
Authentication
PHP ^8.316 pages
Docs for v0.1.0, from GitHub.
Pages in these docs
An authenticator adds credentials to each request. It runs last, just before the HTTP client, so:
- a retried request is authenticated afresh;
- nothing earlier in the pipeline, a logger included, sees the credentials.
Static credentials
| Authenticator | Sends |
|---|---|
new BearerToken($token) | Authorization: Bearer <token> (RFC 6750 §2.1) |
new BasicAuth($user, $password) | Authorization: Basic ... (RFC 7617) |
new HeaderKey('X-Api-Key', $key) | the key in a header of the API’s choosing |
new QueryKey('api_key', $key) | the key in the query string, for APIs that give no other choice |
The header or parameter a HeaderKey or QueryKey writes to is masked in exceptions and logs, whatever it’s called. Writing your own Authenticator, mark the request parameter of authenticate() (and refresh(), for Refreshable) with #[\SensitiveParameter], give any class holding a secret a __debugInfo(), and keep the secret in a constructor parameter marked the same way: the authenticated request is on the stack whenever a transport failure is raised (Security). QueryKey also replaces any value a request’s own query had for that parameter, so a caller can’t swap in a different key.
No credentials over plain HTTP
A connector with an authenticator and an http:// base URI refuses to be built. Credentials over an unencrypted channel are what draft-ietf-httpapi-privacy says a client MUST NOT send. For a local server, say so:
parent::__construct(baseUri: 'http://localhost:8080', auth: $auth, insecure: true);OAuth 2.0
Describe the client registration once:
$oauth = new OAuthClient( tokenEndpoint: 'https://auth.acme.test/oauth/token', clientId: $id, clientSecret: $secret, // null for a public client: a CLI, a mobile app authorizationEndpoint: 'https://auth.acme.test/oauth/authorize', deviceAuthorizationEndpoint: 'https://auth.acme.test/oauth/device',);- TLS: every endpoint has to be HTTPS, unless you pass
insecure: true. - Client authentication uses HTTP Basic. Following RFC 6749 §2.3.1, the ID and secret are form-encoded before Basic encoding, which is the step most clients miss: a secret with a
+in it fails without it. Passauthentication: ClientAuthentication::Postfor servers that want them in the body instead. - The token endpoint is called directly over PSR-18, not through your connector. It’s usually another host with different rules.
- From the server’s metadata:
OAuthClient::fromMetadata($metadata, $id, $secret)reads the token, authorisation, device authorisation and revocation endpoints from an RFC 8414 metadata document you’ve fetched and decoded. Fetch it from/.well-known/oauth-authorization-serverunder the issuer, and check itsissueris the one you expected (§3.3); the toolbox doesn’t fetch it for you. - Scopes are listed with spaces, as RFC 6749 §3.3 says. Some servers (Todoist among them) want commas instead: pass
scopeSeparator: ',', and every flow sends them that way and reads the granted scopes back the same way.
Server to server: client credentials
parent::__construct( baseUri: 'https://api.acme.test', auth: new ClientCredentials($oauth, scopes: ['projects:read']),);It fetches a token the first time one’s needed and reuses it until 30 seconds before it expires. It needs a confidential client (one with a secret), as RFC 6749 §4.4 says.
For a user: authorisation code with PKCE
Start the flow, and keep what it gives you in the session:
$flow = new AuthorizationCode($oauth, redirectUri: 'https://app.test/oauth/callback');
$started = $flow->start(['projects:read', 'offline']);$session->put('acme_oauth', $started);
return redirect($started->url);When the user comes back:
$started = $session->pull('acme_oauth');$token = $flow->exchange($started, $request->query('code'), $request->query('state'));
$store->put("user:{$user->id}", $token);- PKCE is used for every client, confidential ones included, as RFC 9700 recommends. It’s always S256, never
plain. - The returned
stateis checked in constant time. A mismatch throwsOAuthExceptionwith the errorinvalid_statebefore anything is sent.
From then on, RefreshingToken keeps that user’s token fresh:
auth: new RefreshingToken($oauth, "user:{$user->id}", $store, $lock),It refreshes shortly before expiry, and replaces the refresh token whenever the server issues a new one, as RFC 6749 §6 requires. With no refresh token left it throws OAuthException (no_refresh_token): the user has to authorise again.
When a reply has no refresh token, the old one is kept, as RFC 6749 §6 allows. A server that rotates refresh tokens (RFC 9700 §4.14.2) can instead omit it because the old one is already spent: Todoist does this when a refresh is retried within its grace window, and presenting the spent token later reads as a replay that revokes the user’s whole grant. Pass rotating: true for such a server, and a reply without a refresh token leaves none stored.
For a CLI: the device flow
$flow = new DeviceAuthorization($oauth);
$code = $flow->start(['projects:read']);echo "Go to {$code->verificationUri} and enter {$code->userCode}\n";
$token = $flow->poll($code);Polling follows RFC 8628 §3.5:
- it waits
intervalseconds (5 if the server gives none); - it adds 5 more on every
slow_down; - it doubles the wait after a connection failure;
- it stops on a denial or when the code expires.
A grant the toolbox doesn’t have
TokenProvider is what ClientCredentials and RefreshingToken are built on: it stores the token, fetches a new one when it expires, once across processes, and never hands out one the API rejected. Give it a fetch for any other grant, such as RFC 7523’s JWT bearer grant or RFC 8693’s token exchange, and send what it hands out with ProvidedToken:
auth: new ProvidedToken(new TokenProvider( key: 'acme:jwt-bearer', store: $store, lock: $lock, clock: $oauth->clock, fetch: fn (?AccessToken $current): AccessToken => $oauth->requestToken([ 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $assertions->make(), ]),)),fetch gets the token being replaced, if there is one, so a refresh-style grant can use it. A 401 renews the token and retries once, as with the built-in grants.
Registering a client at runtime
Software that can’t be registered by hand, such as one client per installation, an agent or a multi-tenant integration, can register itself (RFC 7591):
$client = (new ClientRegistration('https://auth.acme.test/register'))->register(new ClientMetadata( redirectUris: ['https://app.test/callback'], clientName: 'My App', grantTypes: ['authorization_code', 'refresh_token'],));
$oauth = $client->oauthClient('https://auth.acme.test/oauth/token', 'https://auth.acme.test/oauth/authorize');- The metadata follows RFC 7591 §2, including its defaults:
authorization_codeas the only grant, andclient_secret_basicto authenticate. UsetokenEndpointAuthMethod: 'none'for a public client, andextra:for anything else the server takes. - An initial access token, for a server that wants one, is the second argument to
register(), sent as a Bearer token. - What comes back is what the server registered, which can differ from what you asked for.
oauthClient()authenticates the way it was registered to: Basic, the body, or nothing for a public client. A method the toolbox can’t use, such asprivate_key_jwt, throws. - The secret, and the registration access token if the server issues one (RFC 7592), are credentials:
clientSecret()andregistrationAccessToken()return them, and they’re kept out of dumps. Aclient_secret_expires_atof 0 means it never expires, and reads as null. - A refusal (§3.2.2, such as
invalid_redirect_uri) throwsOAuthException.
Revoking a token
At sign-out, or when a token may have leaked, revoke it so it stops working before it expires (RFC 7009). The client needs a revocation endpoint: pass revocationEndpoint, or build it with fromMetadata() from a server that publishes revocation_endpoint. Without one, revoke() throws InvalidRequestException and sends nothing.
$oauth->revoke($refreshToken, 'refresh_token');$oauth->revoke($accessToken); // an AccessToken is hinted as access_token
(new RefreshingToken($oauth, "user:{$user->id}", $store, $lock))->revoke();- The hint,
token_type_hint, isaccess_tokenorrefresh_token(§2.1). It helps the server look the token up; it doesn’t change what’s revoked. - The client authenticates as it does at the token endpoint: Basic, the body, or just its ID for a public client.
- A 200 is success, and a server answers 200 for a token that was already invalid (§2.2), so revoking twice is safe. Anything else throws
OAuthException, withunsupported_token_typewhen the server can’t revoke that kind of token (§2.2.1). revoke()onRefreshingToken,ClientCredentialsor aTokenProviderrevokes the stored token and forgets it. The refresh token goes first, since revoking it SHOULD end the whole grant, then the access token, as a server needn’t do both. It runs inside the refresh lock, so another process can’t store a fresh token halfway through. The token is forgotten only once the server has accepted it, so a failure leaves it stored to try again; call$store->forget($key)yourself if signing out locally matters more.
When the API rejects a token
If an OAuth authenticator gets a 401, it renews the credentials and sends the request once more (RFC 6750 §3.1).
- What counts: an
invalid_tokenchallenge, or a bare 401 with noWWW-Authenticate, which plenty of APIs send. - What doesn’t: a challenge naming another error, such as
invalid_request, or a 403insufficient_scope. New credentials won’t fix those. - Your own authenticator gets the same behaviour by implementing
Refreshable.
Storing tokens
| Store | For |
|---|---|
InMemoryTokenStore (the default) | one process: a CLI command, a worker |
new Psr16TokenStore($cache) | a web application, or anything with more than one process |
Psr16TokenStore keeps tokens as plain arrays and ignores anything else it finds under its key. It never calls unserialize(), the hole behind Saloon’s v4 remote code execution fix. Tokens are secrets, so use a cache only your application can read.
Refreshing once, across processes
Ten workers that find the same expired token shouldn’t refresh it ten times. With refresh-token rotation, all but the first would be using a refresh token the server has already retired. Every refresh runs inside a RefreshLock, and the first thing it does inside the lock is read the store again. If another process refreshed while this one waited, it uses that token and fetches nothing.
The default ProcessLock only covers one process. With a shared store, adapt your framework’s lock:
final readonly class SymfonyRefreshLock implements RefreshLock{ public function __construct(private LockFactory $locks) {}
public function synchronized(string $key, Closure $callback): mixed { $lock = $this->locks->createLock("token-refresh.{$key}", 30); $lock->acquire(blocking: true);
try { return $callback(); } finally { $lock->release(); } }}A token the API has rejected is never handed out again, even if its expiry says it’s still good.
Not supported
- DPoP (RFC 9449): not supported yet. A token type other than Bearer is refused, as RFC 6749 §7.1 says a client must.
- The implicit grant: not offered. RFC 9700 says not to use it.