MCP PHP SDK

OAuthAuthenticator implements AuthenticatorInterface

FinalYes

Drives the MCP authorization flow when a server answers with a challenge; build one with {@see OAuth}.

Tags
author

Christopher Hertel mail@christopher-hertel.de

Table of Contents

Interfaces

AuthenticatorInterface
Attaches credentials to outgoing HTTP requests and reacts to authentication challenges.

Properties

$audience  : string|null
The resource the current token may be sent to, which stays behind $resource when an authorization fails.
$authorizationHandler  : AuthorizationHandlerInterface
$client  : ClientRegistration|null
$configuration  : OAuthConfiguration
$discovery  : MetadataDiscovery
$issuer  : string|null
$logger  : LoggerInterface
$metadata  : AuthorizationServerMetadata|null
Where the current token came from, so it can be refreshed before it expires.
$noRefreshBeforeSending  : AccessToken|null
Not refreshed before sending: a failed refresh would repeat on every request, and so would a token shorter-lived than the leeway.
$offlineAccessRefused  : bool
$registrar  : ClientRegistrar
$requestedScopes  : array<string|int, string>
$resource  : string|null
$storage  : CredentialStorageInterface
$token  : AccessToken|null
$tokenEndpoint  : TokenEndpoint

Methods

__construct()  : mixed
authenticate()  : RequestInterface
Return the request carrying whatever credentials are currently available.
finishAuthorization()  : void
Completes an authorization that RedirectAuthorizationHandler sent to the browser.
handleChallenge()  : bool
React to a 401 or 403 answer from the resource server.
assertIdentifiesItsResponses()  : void
Refuse an authorization endpoint that may belong to another server, unless its responses can prove they don't.
assertSupportsPkce()  : void
canonicalize()  : string
The canonical URI a token is requested for, without a fragment.
configuredClient()  : ClientRegistration|null
The client identity that needs no registration: a configured client or a client metadata document.
discover()  : AuthorizationServerMetadata, ?string[]}
Find the resource and the server, on every challenge as a resource may move.
discoverLegacyServer()  : AuthorizationServerMetadata
Fall back to the discovery of the 2025-03-26 revision, where a server is its own authorization server.
forgetRefusedClient()  : void
grant()  : AccessToken
grantWithFallback()  : AccessToken, string[]}
Run the grant, and retry without offline_access if it was refused (invalid_scope, or not_allowed from Keycloak).
isForgottenClient()  : bool
isRefusedClient()  : bool
isUsable()  : bool
Whether a stored token is worth trying instead of authorizing again.
isWithinScopeLimit()  : bool
Configurations with the same grant and client share stored tokens, so a stored one may come from a broader configuration.
knownClient()  : ClientRegistration|null
The client identity in use, without registering one.
matchesRedirectUris()  : bool
origin()  : string
reduceScopes()  : array<string|int, string>
refresh()  : AccessToken|null
Trade a refresh token for a new access token, one process at a time as a rotated refresh token can only be spent once.
refreshBeforeSending()  : AccessToken
Saves the round trip of a rejected request; on any failure the server's challenge starts the usual flow.
requestAuthorizationGrant()  : string
Trades the identity token for a grant for this resource and authorization server.
requestToken()  : AccessToken
resolveClient()  : ClientRegistration
Work out which client identity to use with this authorization server.
scopeLimit()  : array<string|int, string>|null
Without a user to consent, the configured scopes are all a client may hold, whatever a server or a stored token names.
selectIssuer()  : string
selectScopes()  : array<string|int, string>
Prefer the scopes of the challenge, then those of the resource, and keep the ones requested before.
spendRefreshToken()  : AccessToken|null
tokenKey()  : string
Where a token is stored: configurations sharing a storage must not take over each other's tokens.
trustedMetadataUrl()  : string|null
The metadata URL of the challenge, unless it would make the client request another origin on the server's behalf.
verifyCallback()  : void
Check the authorization response before spending the code it carries.
withoutEmptyValues()  : array<string, string>

Properties

$audience

The resource the current token may be sent to, which stays behind $resource when an authorization fails.

private string|null $audience = null

$metadata

Where the current token came from, so it can be refreshed before it expires.

private AuthorizationServerMetadata|null $metadata = null

$noRefreshBeforeSending

Not refreshed before sending: a failed refresh would repeat on every request, and so would a token shorter-lived than the leeway.

private AccessToken|null $noRefreshBeforeSending = null

$requestedScopes

private array<string|int, string> $requestedScopes = []

The scopes the last authorization asked for, which a step-up challenge adds to.

Methods

__construct()

public __construct(OAuthConfiguration $configuration, CredentialStorageInterface $storage, AuthorizationHandlerInterface $authorizationHandler, MetadataDiscovery $discovery, ClientRegistrar $registrar, TokenEndpoint $tokenEndpoint[, LoggerInterface $logger = new NullLogger() ]) : mixed
Parameters
$configuration : OAuthConfiguration
$storage : CredentialStorageInterface
$authorizationHandler : AuthorizationHandlerInterface
$discovery : MetadataDiscovery
$registrar : ClientRegistrar
$tokenEndpoint : TokenEndpoint
$logger : LoggerInterface = new NullLogger()

authenticate()

Return the request carrying whatever credentials are currently available.

public authenticate(RequestInterface $request) : RequestInterface

Implementations return the request unchanged when they hold none: the resource server answering with a challenge is what starts the flow.

Parameters
$request : RequestInterface
Return values
RequestInterface

finishAuthorization()

Completes an authorization that RedirectAuthorizationHandler sent to the browser.

public finishAuthorization(array<string, string> $callback) : void
Parameters
$callback : array<string, string>

the query parameters of the request to the redirect URI

Tags
throws
AuthorizationPendingException

when the authorization has to start again without offline_access

AuthorizationException

when the callback does not complete a pending authorization of this storage

handleChallenge()

React to a 401 or 403 answer from the resource server.

public handleChallenge(RequestInterface $request, ResponseInterface $response) : bool
Parameters
$request : RequestInterface

the request that was rejected

$response : ResponseInterface

the rejecting response, carrying the challenge

Return values
bool —

true when credentials were obtained and the request should be retried, false when the authenticator cannot make progress

assertIdentifiesItsResponses()

Refuse an authorization endpoint that may belong to another server, unless its responses can prove they don't.

private assertIdentifiesItsResponses(AuthorizationServerMetadata $metadata) : void

A hostile server can name the endpoint of a real one, and keep the token endpoint. The user signs in at the real address, and the code goes to the hostile server unless the response names its issuer (RFC 9700 section 4.4).

Parameters
$metadata : AuthorizationServerMetadata

assertSupportsPkce()

private static assertSupportsPkce(AuthorizationServerMetadata $metadata) : void
Parameters
$metadata : AuthorizationServerMetadata

canonicalize()

The canonical URI a token is requested for, without a fragment.

private static canonicalize(string $url) : string
Parameters
$url : string
Return values
string

configuredClient()

The client identity that needs no registration: a configured client or a client metadata document.

private configuredClient(AuthorizationServerMetadata $metadata) : ClientRegistration|null
Parameters
$metadata : AuthorizationServerMetadata
Return values
ClientRegistration|null

discover()

Find the resource and the server, on every challenge as a resource may move.

private discover(string $endpoint, AuthorizationChallenge $challenge) : AuthorizationServerMetadata, ?string[]}
Parameters
$endpoint : string
$challenge : AuthorizationChallenge
Return values
AuthorizationServerMetadata, ?string[]}

discoverLegacyServer()

Fall back to the discovery of the 2025-03-26 revision, where a server is its own authorization server.

private discoverLegacyServer(string $endpoint) : AuthorizationServerMetadata
Parameters
$endpoint : string
Return values
AuthorizationServerMetadata

grantWithFallback()

Run the grant, and retry without offline_access if it was refused (invalid_scope, or not_allowed from Keycloak).

private grantWithFallback(AuthorizationServerMetadata $metadata, ClientRegistration $client, array<string|int, string> $scopes, string $resource) : AccessToken, string[]}
Parameters
$metadata : AuthorizationServerMetadata
$client : ClientRegistration
$scopes : array<string|int, string>
$resource : string
Return values
AccessToken, string[]}

isUsable()

Whether a stored token is worth trying instead of authorizing again.

private isUsable(AccessToken $token, array<string|int, string> $scopes, RequestInterface $request) : bool
Parameters
$token : AccessToken
$scopes : array<string|int, string>
$request : RequestInterface
Return values
bool

isWithinScopeLimit()

Configurations with the same grant and client share stored tokens, so a stored one may come from a broader configuration.

private isWithinScopeLimit(AccessToken $token) : bool
Parameters
$token : AccessToken
Return values
bool

origin()

private static origin(string $url) : string
Parameters
$url : string
Return values
string

refresh()

Trade a refresh token for a new access token, one process at a time as a rotated refresh token can only be spent once.

private refresh(AccessToken|null $stored, AuthorizationServerMetadata $metadata, ClientRegistration $client, array<string|int, string> $scopes, string $resource, RequestInterface $request) : AccessToken|null
Parameters
$stored : AccessToken|null
$metadata : AuthorizationServerMetadata
$client : ClientRegistration
$scopes : array<string|int, string>
$resource : string
$request : RequestInterface
Return values
AccessToken|null

refreshBeforeSending()

Saves the round trip of a rejected request; on any failure the server's challenge starts the usual flow.

private refreshBeforeSending(AccessToken $token, RequestInterface $request, string $resource) : AccessToken
Parameters
$token : AccessToken
$request : RequestInterface
$resource : string
Return values
AccessToken

requestAuthorizationGrant()

Trades the identity token for a grant for this resource and authorization server.

private requestAuthorizationGrant(AuthorizationServerMetadata $metadata, array<string|int, string> $scopes, string $resource) : string
Parameters
$metadata : AuthorizationServerMetadata
$scopes : array<string|int, string>
$resource : string
Return values
string

resolveClient()

Work out which client identity to use with this authorization server.

private resolveClient(AuthorizationServerMetadata $metadata, array<string|int, string> $scopes, array<string|int, string>|null $scopesSupported) : ClientRegistration
Parameters
$metadata : AuthorizationServerMetadata
$scopes : array<string|int, string>
$scopesSupported : array<string|int, string>|null
Return values
ClientRegistration

scopeLimit()

Without a user to consent, the configured scopes are all a client may hold, whatever a server or a stored token names.

private scopeLimit() : array<string|int, string>|null
Return values
array<string|int, string>|null

selectIssuer()

private selectIssuer(string $endpoint, array<string|int, string> $authorizationServers) : string
Parameters
$endpoint : string
$authorizationServers : array<string|int, string>
Return values
string

selectScopes()

Prefer the scopes of the challenge, then those of the resource, and keep the ones requested before.

private selectScopes(AuthorizationChallenge $challenge, array<string|int, string>|null $scopesSupported, AuthorizationServerMetadata $metadata, AccessToken|null $stored) : array<string|int, string>
Parameters
$challenge : AuthorizationChallenge
$scopesSupported : array<string|int, string>|null
$metadata : AuthorizationServerMetadata
$stored : AccessToken|null
Return values
array<string|int, string>

tokenKey()

Where a token is stored: configurations sharing a storage must not take over each other's tokens.

private tokenKey(string $resource) : string
Parameters
$resource : string
Return values
string

trustedMetadataUrl()

The metadata URL of the challenge, unless it would make the client request another origin on the server's behalf.

private static trustedMetadataUrl(string $endpoint, AuthorizationChallenge $challenge) : string|null
Parameters
$endpoint : string
$challenge : AuthorizationChallenge
Return values
string|null

verifyCallback()

Check the authorization response before spending the code it carries.

private verifyCallback(array<string, string> $callback, string $state, AuthorizationServerMetadata $metadata) : void
Parameters
$callback : array<string, string>
$state : string
$metadata : AuthorizationServerMetadata
Tags
phpstan-assert

non-empty-array{code: string} $callback

withoutEmptyValues()

private static withoutEmptyValues(array<string, string|null> $parameters) : array<string, string>
Parameters
$parameters : array<string, string|null>
Return values
array<string, string>
On this page

Search results