Development
How to Build an OAuth Callback in PHP

An OAuth callback receives an authorization response from a provider and completes an authorization-code flow. The callback must bind that response to the browser session that started the flow, exchange the code securely, and store tokens according to the application's access policy.
OAuth grants access to a resource. If the application needs to sign a user in, use the provider's supported identity protocol, commonly OpenID Connect, and validate its identity response. An access token alone is not a universal user identity.
Record the OAuth transaction before redirecting
Use a maintained OAuth client compatible with your provider. Before sending the browser to authorization, create a cryptographically random state, a PKCE verifier and challenge using S256, an expiry, and the intended local continuation route.
Store those values server-side in the session. Use a fixed allowlisted continuation path rather than accepting an arbitrary return URL. Parallel authorization attempts need distinct transaction records so one tab does not overwrite another's state.
The redirect URI registered with the provider must match the actual callback. Configure the public origin explicitly; do not construct it from an untrusted Host or forwarding header.
Validate the callback before token exchange
The following PHP 8.1 function illustrates checking one session-backed transaction. It assumes the session is already active and that the start endpoint stored a record under oauth_transaction.
<?php
/** Consume a matching, unexpired authorization transaction. */
function consumeOAuthTransaction(array $query): array
{
$transaction = $_SESSION['oauth_transaction'] ?? null;
$state = $query['state'] ?? null;
if (!is_array($transaction)
|| !isset($transaction['state'], $transaction['expires_at'], $transaction['verifier'])
|| !is_string($transaction['state']) || !is_string($state)
|| !is_int($transaction['expires_at'])
|| !is_string($transaction['verifier'])
|| $transaction['expires_at'] <= time()
|| !hash_equals($transaction['state'], $state)) {
throw new RuntimeException('Invalid authorization response.');
}
unset($_SESSION['oauth_transaction']);
return $transaction;
}
This single-transaction example intentionally does not implement a complete OAuth client. After consuming the transaction, handle a provider error response, require a nonempty scalar authorization code, and pass the saved verifier to the client's token exchange.
Do not exchange a code when the state check fails. Do not put client secrets, token responses, or authorization codes into logs or error pages.
Let the library handle protocol details
Use HTTPS token endpoints from trusted provider configuration, an exact redirect URI, and the authentication method required for your client type. Set bounded network timeouts. Never allow a query parameter to choose the token endpoint; that can expose credentials to an attacker-controlled server.
The OAuth security best current practice and PKCE specification describe the relevant protections. Provider-specific discovery, scopes, and token behavior still require official documentation and integration tests.
For OpenID Connect, validate issuer, audience, signature, expiry, and the transaction's nonce using a maintained implementation. Do not manually decode a JWT and treat its unsigned contents as verified identity.
Store and refresh tokens deliberately
Keep tokens server-side and associate them with the correct local account and provider connection. Encrypt sensitive token material at rest using a deployment-managed key, limit application access, and plan revocation and deletion.
Refresh-token rotation needs concurrency control. Two workers refreshing the same connection can overwrite the newest token or invalidate the connection. Serialize refresh for that connection and persist the returned token set atomically.
After a successful callback, redirect to a clean local URL so the browser address no longer contains the code and state. Use restrictive caching and referrer policies on the callback response.
Test failure and replay cases
Test consent denial, wrong state, expired transaction, array-shaped query values, reused callback, token endpoint timeout, wrong redirect URI, and a connection linked to the wrong local user. Use the provider's sandbox or a controlled test account, without exposing real tokens.
See isolating changes in a legacy PHP application for the surrounding refactor, or discuss an OAuth integration review.