OAuth
suggest changeOAuth 2.0 lets a user give your application limited access to their account on another service (Google, GitHub, Microsoft, Slack) without giving you their password. The service hands your app an access token, and you send that token with each API request.
OAuth is also the base for "Log in with Google/GitHub". That part is OpenID Connect (OIDC), a thin layer on top of OAuth 2.0 that adds an ID token describing who the user is.
The roles:
| Role | Who it is |
|---|---|
| Resource owner | the user |
| Client | your PHP application |
| Authorization server | issues tokens, e.g. https://accounts.google.com |
| Resource server | the API you call with the token, e.g. https://api.github.com |
The grant types (flows) you will use in practice:
| Flow | When |
|---|---|
| Authorization code + PKCE | a user logs in through a browser (web apps, mobile, SPAs) |
| Client credentials | server-to-server, no user involved |
| Refresh token | getting a new access token when the old one expires |
| Device code | CLI tools and TVs without a browser |
The implicit flow and the password grant are deprecated (OAuth 2.1 removes them). Do not use them in new code.
Registering your app
Before writing code, register an application with the provider. You get:
- a client ID (public, it appears in URLs)
- a client secret (private, keep it out of the repository)
- one or more redirect URIs you register, e.g.
https://example.com/oauth/callback
The provider only redirects to a registered URI, and it must match exactly, including scheme, host, port and path.
Keep the credentials in environment variables:
<?php
$config = [
'client_id' => getenv('OAUTH_CLIENT_ID'),
'client_secret' => getenv('OAUTH_CLIENT_SECRET'),
'redirect_uri' => 'https://example.com/oauth/callback.php',
'authorize_url' => 'https://github.com/login/oauth/authorize',
'token_url' => 'https://github.com/login/oauth/access_token',
];
Authorization code flow with PKCE, by hand
Doing the flow once without a library shows what every library does for you. It has three steps:
- Redirect the user to the provider's authorize URL.
- The user logs in and approves. The provider redirects back to your redirect URI with
?code=...&state=.... - Your server exchanges the code for tokens with a POST to the token URL.
Two random values protect the flow:
- state stops cross-site request forgery: an attacker cannot make your callback accept a code they obtained. You store it in the session and compare it on the way back.
- PKCE (Proof Key for Code Exchange) binds the code to your session: you send a hash of a secret (
code_challenge) at step 1 and the secret itself (code_verifier) at step 3. A stolen code is useless without the verifier. PKCE is recommended for every client, including server-side apps with a client secret.
Helper for base64url encoding, used by PKCE (and JWTs):
<?php
function base64url_encode(string $bytes): string
{
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}
$verifier = base64url_encode(random_bytes(32));
$challenge = base64url_encode(hash('sha256', $verifier, true));
echo $verifier, "\n", $challenge, "\n";
Output (random each time):
q3Hn1y0cV2m8kZ0Jx4pQeTqk9P7wF2sL0aXbYvR6uNc
0dYk2LQe4c8n8Hk9Fv1sG3vJpZbM5mWcT7rXq2yLh4A
The verifier must be 43 to 128 characters; 32 random bytes encode to 43.
Step 1: redirect to the provider
login.php:
<?php
session_start();
require __DIR__ . '/config.php'; // defines $config
require __DIR__ . '/base64url.php'; // defines base64url_encode()
$state = bin2hex(random_bytes(16));
$verifier = base64url_encode(random_bytes(32));
$_SESSION['oauth_state'] = $state;
$_SESSION['oauth_verifier'] = $verifier;
$params = [
'response_type' => 'code',
'client_id' => $config['client_id'],
'redirect_uri' => $config['redirect_uri'],
'scope' => 'read:user user:email',
'state' => $state,
'code_challenge' => base64url_encode(hash('sha256', $verifier, true)),
'code_challenge_method' => 'S256',
];
header('Location: ' . $config['authorize_url'] . '?' . http_build_query($params));
exit;
http_build_query() URL-encodes the values; it encodes spaces as +, which providers accept in query strings. Scopes are separated by spaces, and their names are defined by each provider.
Step 2 and 3: handle the callback and exchange the code
callback.php:
<?php
session_start();
require __DIR__ . '/config.php';
// The user clicked "Cancel", or the provider rejected the request.
if (isset($_GET['error'])) {
http_response_code(400);
exit('Authorization failed: ' . htmlspecialchars($_GET['error']));
}
$state = $_SESSION['oauth_state'] ?? '';
$verifier = $_SESSION['oauth_verifier'] ?? '';
unset($_SESSION['oauth_state'], $_SESSION['oauth_verifier']); // single use
if ($state === '' || !hash_equals($state, (string)($_GET['state'] ?? ''))) {
http_response_code(400);
exit('Invalid state');
}
$ch = curl_init($config['token_url']);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'authorization_code',
'code' => (string)($_GET['code'] ?? ''),
'redirect_uri' => $config['redirect_uri'],
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'code_verifier' => $verifier,
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($body === false) {
throw new RuntimeException('Token request failed: ' . curl_error($ch));
}
$token = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if ($status !== 200 || isset($token['error'])) {
http_response_code(502);
exit('Token error: ' . htmlspecialchars($token['error_description'] ?? $token['error'] ?? 'unknown'));
}
session_regenerate_id(true); // the user's privilege level changed
$_SESSION['access_token'] = $token['access_token'];
$_SESSION['refresh_token'] = $token['refresh_token'] ?? null;
$_SESSION['expires_at'] = isset($token['expires_in']) ? time() + (int)$token['expires_in'] : null;
header('Location: /');
exit;
A typical token response:
{
"access_token": "gho_16C7e42F292c6912E7710c838347Ae178B4a",
"token_type": "bearer",
"expires_in": 28800,
"refresh_token": "ghr_1B4a2e77838347a7E420ce178F2E7c6912E1",
"scope": "read:user,user:email"
}
Notes:
- Passing an array to
CURLOPT_POSTFIELDSsendsmultipart/form-data. The token endpoint expectsapplication/x-www-form-urlencoded, so pass a string fromhttp_build_query(). - Some providers (GitHub among them) return form-encoded data unless you send
Accept: application/json. - Many providers prefer the client credentials in an
Authorization: Basicheader (client_secret_basic) instead of the body. With cURL:CURLOPT_USERPWD => urlencode($id) . ':' . urlencode($secret). - Compare secrets with
hash_equals(), not===, to avoid timing leaks. See Cross-Site Request Forgery for more on tokens in forms. - Authorization codes are single use and expire within minutes. Reloading the callback page fails the second time; that is expected.
Calling the API with the access token
Send the token in the Authorization header with the Bearer scheme:
<?php
function api_get(string $url, string $accessToken): array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $accessToken,
'Accept: application/json',
'User-Agent: my-php-app', // GitHub rejects requests without it
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
if ($status === 401) {
throw new RuntimeException('Token expired or revoked');
}
return json_decode($body, true, flags: JSON_THROW_ON_ERROR);
}
$user = api_get('https://api.github.com/user', $_SESSION['access_token']);
echo $user['login'], ' (', $user['id'], ")\n";
Output:
octocat (583231)
Never put the token in the URL query string (?access_token=...): URLs end up in server logs, browser history and Referer headers.
Refreshing an expired token
Access tokens are short-lived (minutes to hours). If the provider issued a refresh token, use it to get a new access token without sending the user through the login again:
<?php
function refresh_access_token(array $config, string $refreshToken): array
{
$ch = curl_init($config['token_url']);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_USERPWD => urlencode($config['client_id']) . ':' . urlencode($config['client_secret']),
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
]),
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
$token = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if (isset($token['error'])) {
// invalid_grant: refresh token expired or revoked, the user must log in again
throw new RuntimeException($token['error']);
}
return $token;
}
// Refresh a little early so the token does not expire mid-request.
if ($_SESSION['expires_at'] !== null && $_SESSION['expires_at'] - 60 < time()) {
$token = refresh_access_token($config, $_SESSION['refresh_token']);
$_SESSION['access_token'] = $token['access_token'];
$_SESSION['expires_at'] = time() + (int)$token['expires_in'];
// Many providers rotate refresh tokens: always store the new one if present.
if (isset($token['refresh_token'])) {
$_SESSION['refresh_token'] = $token['refresh_token'];
}
}
Google only returns a refresh token when you add access_type=offline (and, to get it again for an existing user, prompt=consent) to the authorize URL. Microsoft and others require the offline_access scope.
If you store refresh tokens in a database to act on the user's behalf later, treat them like passwords: encrypt them at rest (see Cryptography) and delete them when the user disconnects your app.
Using league/oauth2-client
In real code use a library. league/oauth2-client is the standard one, with official and community providers for Google, GitHub, Microsoft, Facebook and many others.
composer require league/oauth2-client
GenericProvider works with any standards-compliant server:
<?php
require __DIR__ . '/vendor/autoload.php';
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\GenericProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
session_start();
$provider = new GenericProvider([
'clientId' => getenv('OAUTH_CLIENT_ID'),
'clientSecret' => getenv('OAUTH_CLIENT_SECRET'),
'redirectUri' => 'https://example.com/oauth.php',
'urlAuthorize' => 'https://auth.example.com/oauth2/authorize',
'urlAccessToken' => 'https://auth.example.com/oauth2/token',
'urlResourceOwnerDetails' => 'https://auth.example.com/oauth2/userinfo',
'scopes' => ['openid', 'profile', 'email'],
'scopeSeparator' => ' ',
'pkceMethod' => AbstractProvider::PKCE_METHOD_S256,
]);
if (!isset($_GET['code'])) {
// Step 1: getAuthorizationUrl() generates state and the PKCE verifier.
$url = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
$_SESSION['oauth2pkce'] = $provider->getPkceCode();
header('Location: ' . $url);
exit;
}
// Step 2: callback
$expected = $_SESSION['oauth2state'] ?? '';
unset($_SESSION['oauth2state']);
if ($expected === '' || !hash_equals($expected, (string)($_GET['state'] ?? ''))) {
exit('Invalid state');
}
try {
$provider->setPkceCode($_SESSION['oauth2pkce']);
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code'],
]);
$owner = $provider->getResourceOwner($accessToken);
print_r($owner->toArray());
echo $accessToken->getToken(), "\n";
echo $accessToken->getRefreshToken(), "\n";
echo date('c', $accessToken->getExpires()), "\n";
} catch (IdentityProviderException $e) {
// The server returned an OAuth error (invalid_grant, invalid_client, ...).
exit('OAuth error: ' . $e->getMessage());
}
Store the token with $accessToken->jsonSerialize() and restore it with new AccessToken($array). Refreshing and other grants use the same method:
<?php
use League\OAuth2\Client\Token\AccessToken;
$accessToken = new AccessToken($_SESSION['token']);
if ($accessToken->hasExpired()) {
$accessToken = $provider->getAccessToken('refresh_token', [
'refresh_token' => $accessToken->getRefreshToken(),
]);
$_SESSION['token'] = $accessToken->jsonSerialize();
}
// Make an authenticated PSR-7 request and parse the JSON response.
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.example.com/v1/projects',
$accessToken
);
$projects = $provider->getParsedResponse($request);
For a specific provider install its package and drop the URLs, for example composer require league/oauth2-github and new League\OAuth2\Client\Provider\Github([...]), or league/oauth2-google.
Client credentials: server to server
When your backend calls another service on its own behalf (no user), use the client credentials grant. There is no redirect, state or PKCE:
<?php
$provider = new GenericProvider([
'clientId' => getenv('OAUTH_CLIENT_ID'),
'clientSecret' => getenv('OAUTH_CLIENT_SECRET'),
'urlAuthorize' => '',
'urlAccessToken' => 'https://auth.example.com/oauth2/token',
'urlResourceOwnerDetails' => '',
]);
$token = $provider->getAccessToken('client_credentials', [
'scope' => 'reports:read',
]);
echo $token->getToken(), "\n";
echo $token->getExpires() - time(), " seconds left\n";
Output:
eyJhbGciOiJSUzI1NiIsImtpZCI6ImsxIn0.eyJpc3MiOi...
3599 seconds left
Cache this token (in APCu, Redis or a file) until shortly before it expires instead of requesting a new one for every PHP request. Token endpoints are rate-limited. See Cache.
Verifying an OpenID Connect ID token
With OIDC (scope openid), the token response also contains an id_token: a JWT signed by the provider that says who logged in. Before trusting it, verify the signature with the provider's public keys (published as JWKS) and check the claims.
composer require firebase/php-jwt
<?php
require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
function verify_id_token(string $idToken, string $clientId, string $nonce): stdClass
{
$issuer = 'https://accounts.google.com';
// From https://accounts.google.com/.well-known/openid-configuration ("jwks_uri").
// Cache this; providers rotate keys, so refetch when a "kid" is unknown.
$jwks = json_decode(
file_get_contents('https://www.googleapis.com/oauth2/v3/certs'),
true,
flags: JSON_THROW_ON_ERROR
);
JWT::$leeway = 60; // allow 60 seconds of clock skew
// Checks the signature, the algorithm (from the key) and exp/nbf/iat.
$claims = JWT::decode($idToken, JWK::parseKeySet($jwks));
if ($claims->iss !== $issuer) {
throw new UnexpectedValueException('Wrong issuer');
}
if (!in_array($clientId, (array)$claims->aud, true)) {
throw new UnexpectedValueException('Token is for another client');
}
if (!hash_equals($nonce, $claims->nonce ?? '')) {
throw new UnexpectedValueException('Nonce mismatch');
}
return $claims;
}
$claims = verify_id_token($token['id_token'], $config['client_id'], $_SESSION['oauth_nonce']);
echo $claims->sub, ' ', $claims->email, "\n";
Output:
110169484474386276334 jane@example.com
JWT::decode()throwsExpiredException,SignatureInvalidExceptionorUnexpectedValueExceptionon failure.nonceis another random value: generate it in step 1, send it as thenonceparameter of the authorize URL and store it in the session, likestate.- Identify users by
iss+sub, never byemail. Email addresses can change and on some providers are not verified (checkemail_verified). firebase/php-jwtalso hasCachedKeySet, which fetches and caches the JWKS through a PSR-6 cache and refreshes it on an unknownkid.
Protecting your own API with bearer tokens
If you are the resource server, read the token from the Authorization header and validate it. For JWT access tokens issued by an external authorization server (Auth0, Keycloak, Entra ID, Cognito), the check looks like the ID token one, but with aud set to your API's identifier:
<?php
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
function bearer_token(): ?string
{
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (preg_match('/^Bearer\s+(\S+)$/i', $header, $m)) {
return $m[1];
}
return null;
}
function deny(int $status, string $error): never
{
http_response_code($status);
header('WWW-Authenticate: Bearer error="' . $error . '"');
header('Content-Type: application/json');
echo json_encode(['error' => $error]);
exit;
}
$jwt = bearer_token() ?? deny(401, 'invalid_request');
try {
$claims = JWT::decode($jwt, JWK::parseKeySet(load_cached_jwks()));
} catch (Throwable) {
deny(401, 'invalid_token');
}
if ($claims->iss !== 'https://auth.example.com/'
|| !in_array('https://api.example.com', (array)$claims->aud, true)) {
deny(401, 'invalid_token');
}
$scopes = explode(' ', $claims->scope ?? '');
if (!in_array('reports:read', $scopes, true)) {
deny(403, 'insufficient_scope');
}
echo json_encode(['user' => $claims->sub, 'reports' => []]);
load_cached_jwks() stands for your own function that returns the decoded JWKS from a cache.
Apache with PHP-FPM or CGI may strip the Authorization header. If $_SERVER['HTTP_AUTHORIZATION'] is empty, add this to .htaccess:
CGIPassAuth On
Opaque (non-JWT) tokens cannot be checked locally; send them to the server's introspection endpoint (RFC 7662) and cache the result briefly.
To build an authorization server yourself use league/oauth2-server, or Laravel Passport, which is built on it. Writing one from scratch is not worth the risk.
Security checklist
- Always use HTTPS for redirect URIs and token requests; see TLS and HTTPS.
- Use authorization code + PKCE, a random
statechecked withhash_equals(), andnoncefor OIDC. - Register exact redirect URIs; never build the redirect URI from user input.
- Keep the client secret on the server. Browser JavaScript and mobile apps are public clients and must not hold one.
- Request the smallest set of scopes you need.
- Keep tokens server-side (in the session or an encrypted database column), not in
localStorageor cookies readable by JavaScript. Configure the session cookie withSecure,HttpOnlyandSameSite=Lax; see Sessions.SameSite=Strictbreaks the flow, because the browser does not send the session cookie on the redirect back from the provider. - Call
session_regenerate_id(true)after login. - Never log tokens, codes or the client secret.