PHP Quickstart
Integrate UniAuth in a PHP app using league/oauth2-client — a third-party OAuth/OIDC library used by this source example — plus firebase/php-jwt for ID-token verification. No UniAuth-specific PHP SDK required.
Read advertised endpoints from discovery and verify each value and profile you use; metadata does not guarantee future compatibility.
https://uniauth.id/.well-known/openid-configuration1. Install
composer require league/oauth2-client firebase/php-jwt guzzlehttp/guzzle2. Fetch & cache discovery
Cache according to your deployment needs, then use and validate only the advertised fields required by the client.
<?php
declare(strict_types=1);
function uniauth_discovery(): array {
static $mem;
if ($mem) return $mem;
$cacheFile = sys_get_temp_dir() . '/uniauth_discovery.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 86400)) {
return $mem = json_decode(file_get_contents($cacheFile), true);
}
$ctx = stream_context_create(['http' => ['timeout' => 5]]);
$json = file_get_contents(
'https://uniauth.id/.well-known/openid-configuration',
false, $ctx
);
if ($json === false) {
throw new RuntimeException('Failed to fetch UniAuth discovery document');
}
file_put_contents($cacheFile, $json);
return $mem = json_decode($json, true);
}
function uniauth_jwks(): array {
static $mem;
if ($mem) return $mem;
$cacheFile = sys_get_temp_dir() . '/uniauth_jwks.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 86400)) {
return $mem = json_decode(file_get_contents($cacheFile), true);
}
$d = uniauth_discovery();
$json = file_get_contents($d['jwks_uri']);
file_put_contents($cacheFile, $json);
return $mem = json_decode($json, true);
}3. Configure the OAuth client
<?php
require 'vendor/autoload.php';
require 'discovery.php';
use League\OAuth2\Client\Provider\GenericProvider;
$d = uniauth_discovery();
$provider = new GenericProvider([
'clientId' => $_ENV['UNIAUTH_CLIENT_ID'], // "uni_xxxxxxxxxxxxxxxx"
'clientSecret' => $_ENV['UNIAUTH_CLIENT_SECRET'], // "unis_xxxxx..."
'redirectUri' => 'https://yourapp.com/callback.php',
'urlAuthorize' => $d['authorization_endpoint'],
'urlAccessToken' => $d['token_endpoint'],
'urlResourceOwnerDetails' => $d['userinfo_endpoint'],
'scopes' => 'openid profile email groups',
'scopeSeparator' => ' ',
'pkceMethod' => 'S256', // enabled here; verify effective client policy
]);Credentials come from the Developer Console. Client IDs begin with uni_ and secrets with unis_. Older clients use unprefixed hex — also valid. If your values don't match the Console exactly, the server returns invalid_client on a friendly error page.
4. Start the login flow
<?php
// login.php
session_start();
require 'config.php'; // sets up $provider from step 3
$url = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
$_SESSION['oauth2pkceCode'] = $provider->getPkceCode();
header('Location: ' . $url);
exit;5. Callback — verify the ID token locally
Exchange the code, then verify the ID token signature using the JWKS. This gives you a verified claim set without hitting /userinfo. Use /userinfo only if you need fresh profile data (e.g. the user just updated their avatar).
<?php
// callback.php
session_start();
require 'config.php';
require 'discovery.php';
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
// 1. Validate state (CSRF)
if (($_GET['state'] ?? '') !== ($_SESSION['oauth2state'] ?? null)) {
http_response_code(400); exit('Invalid state');
}
// 2. Exchange code for tokens
$provider->setPkceCode($_SESSION['oauth2pkceCode']);
$tokenSet = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// 3. Verify the ID token's signature via JWKS (no /userinfo call)
$idToken = $tokenSet->getValues()['id_token'];
$d = uniauth_discovery();
$jwks = uniauth_jwks();
$claims = JWT::decode($idToken, JWK::parseKeySet($jwks));
// Configure and test RS256 signature and exp validation for this exact library version.
// 4. Verify iss + aud (JWT library does NOT do this)
if ($claims->iss !== $d['issuer']) {
http_response_code(400); exit('iss mismatch');
}
$aud = is_array($claims->aud) ? $claims->aud : [$claims->aud];
if (!in_array($_ENV['UNIAUTH_CLIENT_ID'], $aud)) {
http_response_code(400); exit('aud mismatch');
}
// 5. Authorization via claims
if (!($claims->email_verified ?? false)) {
http_response_code(403);
exit('Email not verified — refusing to proceed.');
}
$isAdmin = in_array('admin', $claims->groups ?? []);
// ^ Use the groups claim for RBAC. Don't use env-var email allowlists.
// 6. Local session
$_SESSION['user'] = [
'sub' => $claims->sub, // pairwise — app-specific
'email' => $claims->email,
'name' => $claims->name ?? null,
'groups' => $claims->groups ?? [],
'is_admin' => $isAdmin,
'id_token' => $idToken, // keep for logout
];
header('Location: /');
exit;6. Local Logout and UniAuth Confirmation
Clearing your PHP session ends local login, not the UniAuth browser session. Redirect to end_session_endpoint to request confirmation. Cancelling leaves UniAuth signed in without restoring the PHP session.
<?php
// logout.php
session_start();
require 'discovery.php';
$d = uniauth_discovery();
$idToken = $_SESSION['user']['id_token'] ?? '';
session_destroy();
$params = http_build_query([
'id_token_hint' => $idToken,
'post_logout_redirect_uri' => 'https://yourapp.com/',
]);
header('Location: ' . $d['end_session_endpoint'] . '?' . $params);
exit;7. Back-channel logout webhook
Back-channel logout is a Limited Beta requiring operator-managed enrollment. Its URI must use credential-free, fragment-free HTTPS, and the effective ID-token signing algorithm must be RS256. UniAuth attempts signed JWT POST notifications only to configured, currently authorized RPs with durable, exact ID-token issuance provenance for the retired session. Legacy or unbound sessions produce no recipient. Delivery is not guaranteed; verify received tokens before invalidating matching server-side sessions.
<?php
// logout-webhook.php
require 'vendor/autoload.php';
require 'discovery.php';
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
$d = uniauth_discovery();
$jwks = uniauth_jwks();
$token = $_POST['logout_token'] ?? '';
if (!$token) { http_response_code(400); exit; }
try {
$headers = new \stdClass();
$claims = JWT::decode($token, JWK::parseKeySet($jwks, 'RS256'), $headers);
} catch (Exception $e) {
http_response_code(400); exit;
}
$audience = $claims->aud ?? null;
$aud = is_array($audience) ? $audience : (is_string($audience) ? [$audience] : []);
if (($headers->alg ?? null) !== 'RS256' ||
($headers->typ ?? null) !== 'logout+jwt' ||
($claims->iss ?? null) !== $d['issuer'] ||
!in_array($_ENV['UNIAUTH_CLIENT_ID'], $aud, true) ||
!is_int($claims->iat ?? null) ||
!is_int($claims->exp ?? null) ||
!is_string($claims->jti ?? null) ||
trim($claims->jti) === '') {
http_response_code(400); exit;
}
$sub = is_string($claims->sub ?? null) && trim($claims->sub) !== '' ? $claims->sub : null;
$sid = is_string($claims->sid ?? null) && trim($claims->sid) !== '' ? $claims->sid : null;
$events = $claims->events ?? null;
$event = is_object($events)
? ($events->{'http://schemas.openid.net/event/backchannel-logout'} ?? null)
: null;
if (($sub === null && $sid === null) || !is_object($event)) {
http_response_code(400); exit;
}
// MUST NOT contain nonce (different from ID tokens)
if (property_exists($claims, 'nonce')) { http_response_code(400); exit; }
// Invalidate your DB sessions through a pairwise-sub / issued-sid index.
invalidate_sessions_for_logout($sub, $sid);
http_response_code(200);Integration checklist
Before shipping, rehearse the applicable checks on the Integration Checklist; the checklist is a starting point, not a completeness result. TL;DR: rehearse discovery, PKCE, JWKS, iss/aud/nonce, claims, local/end-session logout, and best-effort back-channel handling for the exact client.
Framework integrations
- • Laravel: use Laravel Socialite as a candidate generic OIDC provider after explicit configuration and profile testing; issuer replacement alone is insufficient.
- • Symfony: evaluate HWIOAuthBundle only as a candidate after exact-version OIDC configuration and profile testing.
- • WordPress: the OpenID Connect Generic plugin is only a candidate for exact-version and profile testing; discovery metadata does not establish compatibility.
Composer source status
The intended Composer identifier uniauth-id/oauth2-client is repository metadata. Its source extends league/oauth2-client. Public Packagist availability is not established; for a reviewed local integration, the generic league/oauth2-client client can use the documented discovery endpoint after profile-specific testing.