Search by

dskripchenko / laravel-oidc

dskripchenko

OpenID Connect for Laravel without a JOSE library: authorization code sign-in with PKCE, provider access tokens for an API (JWT checked against the issuer's JWKS), and group claims to follow — the application decides who the person is.

v0.7.1 2026-11-17 12:48 UTC

This package is auto-updated.

Last update: 2026-11-17 12:58:51 UTC


README

OpenID Connect for Laravel, without a JOSE library:

  • Sign-in through the authorization code flow with PKCE (S256), a state and a nonce kept in the session, the ID token validated against the issuer's JWKS, then the person's userinfo.
  • Provider access tokens for an API: an outside client signed in through the same provider calls the API with the provider's token (a JWT), checked against the issuer's JWKS — RS256/384/512 and ES256/384/512 only, never none or HMAC.
  • Groups from the provider: the claim read, a "blocked" group, roles from group=role pairs, and a freshness rule for tokens without groups.

The package does not decide who the person is in your application: who a subject is, what groups do and what a provider's token may do are yours, through two small contracts.

PHP 8.3+, Laravel 11–13, ext-openssl.

Install

composer require dskripchenko/laravel-oidc
php artisan vendor:publish --tag=oidc-config   # optional
OIDC_ISSUER=https://sso.example.com
OIDC_CLIENT_ID=my-app
OIDC_CLIENT_SECRET=...
OIDC_SCOPES="openid profile email groups"

The provider's endpoints come from <issuer>/.well-known/openid-configuration. The document is kept an hour and taken only when its issuer is the configured one.

Sign-in

The routes and the session are yours; SignInFlow does the protocol.

use Dskripchenko\Oidc\Exceptions\OidcException;
use Dskripchenko\Oidc\OidcClient;
use Dskripchenko\Oidc\SignIn\SignInFlow;

Route::get('/auth/oidc/redirect', function (Request $request, SignInFlow $flow) {
    abort_unless(OidcClient::enabled(), 404);

    return redirect()->away($flow->start($request->session(), ['back' => '/']));
});

Route::get('/auth/oidc/callback', function (Request $request, SignInFlow $flow) {
    try {
        $result = $flow->finish($request);         // state, ID token, userinfo checked
    } catch (OidcException $e) {
        return redirect('/login?sso='.$e->reason()); // state, nonce_mismatch, ...
    }
    $info = $result->user;                          // Dskripchenko\Oidc\UserInfo
    $user = User::firstWhere('oidc_subject', $info->subject)
        ?? User::firstWhere('email', $info->verifiedEmail()); // null unless email_verified === true
    // ... your rules, then:
    Auth::login($user);
    $request->session()->regenerate();

    return redirect($result->context['back']);
});

UserInfo has subject, email (lower case), emailVerified, name (name, else preferred_username), groups (the OIDC_GROUPS_CLAIM claim, null when absent) and the raw claims. verifiedEmail() returns the email only when the provider says email_verified: true — an address it does not vouch for may be anyone's typing and must not match an account.

The state and the nonce are taken out of the session, so a callback works once. finish() requires an ID token in the token response and validates it (OpenID Connect Core, 3.1.3.7) before the userinfo is read:

Check Reason of the ProviderError
the token response has an id_token id_token_missing
signed with RS256 or ES256 by a key of the issuer's JWKS (by kid); never none, HMAC or another algorithm id_token_invalid
iss is the configured issuer id_token_invalid
aud holds OIDC_CLIENT_ID; with several audiences, or any azp, azp is OIDC_CLIENT_ID id_token_invalid
exp not passed and iat not in the future, give or take the leeway id_token_invalid
a non-empty sub id_token_invalid
nonce is the one this sign-in started with nonce_mismatch
the userinfo's sub is the ID token's sub_mismatch

The leeway is OIDC_ID_TOKEN_LEEWAY seconds (oidc.id_token_leeway, 60 by default): the clock difference forgiven between this server and the provider. The validated claims are in $result->idToken.

Silent sign-in

A person signed in to the provider — in another application of the same provider — need not press "Sign in" again. Without a session of its own the application starts a silent sign-in (prompt=none): the provider shows no page, and answers at once.

use Dskripchenko\Oidc\Exceptions\SilentSignInRefused;

// No session here, no refusal remembered, not just signed out:
return redirect()->away($flow->start($request->session(), ['back' => $back], silent: true));

// The callback:
try {
    $result = $flow->finish($request);
} catch (SilentSignInRefused $e) {      // not signed in to the provider
    $request->session()->put('sso_silent_refused', true); // no loop
    return redirect('/login?redirect='.urlencode($e->context['back']));
}

SilentSignInRefused (reason() silent_refused) carries the provider's error — login_required, interaction_required, consent_required or account_selection_required (SignInFlow::SILENT_REFUSALS) — and the context of the start. It is thrown only for a sign-in started silent; any other error, and the same errors after a sign-in that was not silent, stay ProviderError (callback). Do not start a silent sign-in again in the session that was refused, nor right after the person signed out.

More than one client

An application may sign people in through several clients of the same provider — a web interface and a mobile gateway, for instance, each with its own redirect and audiences. Name the others in oidc.clients; each overrides client_id, client_secret, redirect, callback_path and scopes, the issuer stays the one of oidc.issuer:

// config/oidc.php
'clients' => [
    'mobile' => [
        'client_id' => env('OIDC_MOBILE_CLIENT_ID'),
        'client_secret' => env('OIDC_MOBILE_CLIENT_SECRET'),
        'callback_path' => '/mobile/auth/callback',
    ],
],
$mobile = app(OidcClient::class)->as('mobile');
$flow = new SignInFlow($mobile, new IdTokens($mobile, app(IssuerKeys::class)));

The ID token is taken only when it is issued to that client. An unknown name, or one without a client ID, throws ProviderError (client).

Signing out everywhere

Ending the provider's session

Closing the application's own session leaves the person signed in to the provider — and to every other application. logoutUrl() is the provider's page that ends its session (RP-Initiated Logout 1.0); by back-channel logout the provider then tells the other applications.

$idToken = $request->session()->get('oidc_id_token'); // kept at sign-in: $result->tokens->idToken
Auth::logout();
$request->session()->invalidate();
$url = app(OidcClient::class)->logoutUrl($idToken, url('/login?out=1'));

return $url !== null ? redirect()->away($url) : redirect('/login?out=1');

It carries client_id, id_token_hint, post_logout_redirect_uri (register it with the provider) and an optional state. Null when the provider's discovery document has no end_session_endpoint.

Back-channel logout

The provider POSTs a logout token (form field logout_token) to the URL registered for the client when a session there ends: the person signed out elsewhere, an administrator ended it, it expired. LogoutTokens validates it (Back-Channel Logout 1.0, 2.6); the application ends its sessions of that provider session (sid) — or, without one, every session of the person (sub). Keep the ID token's sid and sub with the session at sign-in ($result->idToken).

use Dskripchenko\Oidc\SignOut\LogoutTokens;

Route::post('/auth/oidc/backchannel-logout', function (Request $request, LogoutTokens $tokens) {
    try {
        $logout = $tokens->validate($request->string('logout_token')->toString());
    } catch (OidcException) {
        return response('', 400)->header('Cache-Control', 'no-store');
    }
    // end the sessions with $logout->sessionId, else of $logout->subject
    return response('', 200)->header('Cache-Control', 'no-store');
})->withoutMiddleware(VerifyCsrfToken::class);
Check Reason of the ProviderError
signed with RS256 or ES256 by a key of the issuer's JWKS; never none logout_token_invalid
iss is the configured issuer; aud and azp as for an ID token logout_token_invalid
iat not in the future; exp, when present, not passed; without exp, iat not older than LogoutTokens::MAX_AGE (300 s); give or take the leeway logout_token_invalid
a jti; a sub or a sid; the event http://schemas.openid.net/event/backchannel-logout in events; no nonce logout_token_invalid
the jti not seen before (kept in the cache until the token would expire) logout_token_replayed

For a named client, build it with that client — the token's audience is the client the session was opened with: new LogoutTokens($client->as('mobile'), app(IssuerKeys::class), app('cache.store')).

Calling APIs on behalf of the person

An application that calls another API with the person's access token (a backend for its own frontend) keeps the tokens of the sign-in on the server:

$result = $flow->finish($request);
$tokens = $result->tokens;            // Dskripchenko\Oidc\Tokens\TokenSet
// $tokens->accessToken, ->refreshToken, ->expiresIn, ->refreshExpiresIn, ->idToken

Store them encrypted, next to the session, and never send them to the browser. When the access token expires, trade the refresh token:

use Dskripchenko\Oidc\Exceptions\ProviderError;

try {
    $fresh = app(OidcClient::class)->refresh($stored->refreshToken);
    // keep $fresh->refreshToken ?? $stored->refreshToken
} catch (ProviderError $e) {
    if ($e->reason() === 'refresh_rejected') {
        // blocked, signed out or the session ended at the provider: end the session here too
    }
    // 'refresh': the provider could not answer; try again later
}

The provider refuses the refresh token (refresh_rejected, any 4xx answer) of a person it blocked or signed out, or of a session it ended — so an application that refreshes on its own schedule follows a block within the access token's lifetime. OidcClient::tokens() returns the same refresh token and lifetime in its array; exchange() gives the TokenSet.

Provider access tokens in an API

OIDC_API_TOKENS=true
OIDC_API_AUDIENCE=my-api          # required; not OIDC_CLIENT_ID (see below)
OIDC_API_CLIENTS=chat,mobile      # required: azp / client_id of the token; agent-* — a prefix
OIDC_API_GUARD=sanctum            # optional; the default guard otherwise
use Dskripchenko\Oidc\Http\Middleware\AuthenticateProviderToken;
use Dskripchenko\Oidc\Tokens\ProviderAccessToken;

Route::middleware([AuthenticateProviderToken::class, 'auth:sanctum'])->get('/api/me', function (Request $request) {
    $token = ProviderAccessToken::of($request); // null for any other credential

    return ['user' => $request->user()->id, 'client' => $token?->client];
});

The token also names its scopes ($token->scopes, $token->hasScope('manage')) from its scope claim — a scope matched by its exact name, never by a prefix — so an action can ask for one the provider grants only to some clients.

A bearer that looks like a JWT is checked; any other bearer passes through to your own tokens. A JWT that does not pass gets 401 (TokenRejected), never a second try as something else. A token is taken when:

Check Rejection reason
a well-formed JWS, at most 16 KiB format
alg is RS256/384/512 or ES256/384/512 algorithm
header typ is in OIDC_API_TOKEN_TYPES (default at+jwt, RFC 9068), and the claims do not say ID token (typ: ID, token_use: id) type
signed by a key of the issuer's JWKS, by kid; the key's kty, alg, use and EC curve match the algorithm signature
iss is the issuer issuer
aud holds OIDC_API_AUDIENCE audience
azp (else client_id) is in OIDC_API_CLIENTS — by name, or by a prefix ending in * client
exp not passed, nbf reached (60 s leeway) expired, not_yet
sub names a person SubjectUsers returns subject
groups fresh enough (below) groups_stale

Clients made on the fly (service accounts of agents, one per agent) are taken by a prefix: OIDC_API_CLIENTS=chat,agent-* takes agent-reviewer and agent-writer, not agent- itself; a lone * takes no client. Keep the prefix to clients only your provider's administrators can make.

OIDC_API_AUDIENCE equal to OIDC_CLIENT_ID is ignored — a token for your own sign-in is not one for the API — unless OIDC_API_AUDIENCE_SAME_AS_CLIENT=true. Providers that type access tokens JWT (Keycloak) need OIDC_API_TOKEN_TYPES=at+jwt,JWT; the audience and the client list still keep their ID tokens out.

JWKS. The same keys as for ID tokens (IssuerKeys). Fetched from the discovery document's jwks_uri through the OutboundHttp contract and kept an hour. An unknown kid refetches at most once a minute: a rotated key is picked up, a stream of made-up key IDs does not make the server call out. A failed fetch is remembered for 30 seconds.

Rate limit. After 30 rejected tokens from one address in a minute the address gets 429 (TooManyAttempts, Retry-After). A genuine token — signed by the provider, for your audience and a known client — that is still refused (expired, not_yet, subject, groups_stale) is counted for its holder, the client and the person, not for the address: a service calling on behalf of many people from one address is not slowed down for all of them because of a few. Claims of a token that did not pass the signature, issuer, audience and client checks are never trusted for this. The first 5 rejections of a minute (per address or holder) dispatch ProviderTokenRejected with the reason and the IP — never the token or its claims — for your audit log.

The token grants nothing by itself: decide what a request with ProviderAccessToken::of($request) !== null may do. Do not mint your own long-lived tokens from it: they would outlive the provider's token and its block.

Groups

use Dskripchenko\Oidc\Groups\GroupClaims;
use Dskripchenko\Oidc\Groups\RoleMapping;

GroupClaims::of($claims);          // list<string>|null from OIDC_GROUPS_CLAIM
GroupClaims::blocks($groups);      // in OIDC_BLOCKED_GROUP?

RoleMapping::pairs();              // OIDC_ROLE_GROUPS="admins=admin,auditors=auditor"
RoleMapping::decide($givingGroups, $groups, $heldFromProvider); // RoleChange|null

decide() gives a role to a member of one of its groups, takes over a role held by hand when the person joins its group, and takes back only a role the provider gave — never one given by hand. You store where a role came from and apply the change.

With a groups claim in an access token, GroupSync::sync() runs as at a sign-in (once a minute per person and set of groups); returning false — a blocked person — rejects the token. A token without the claim is taken only while GroupSync::syncedAt() is within OIDC_API_SYNC_MAX_AGE hours (24), and only if GroupSync::followsGroups().

Contracts

Contract Default Bind your own to
Contracts\SubjectUsers EloquentSubjectUsers: the users provider's model (or oidc.users.model) by oidc_issuer and oidc_subject leave out blocked accounts and service accounts
Contracts\GroupSync NullGroupSync: nothing follows groups apply teams, roles, the block
Contracts\OutboundHttp PlainOutboundHttp: timeout, no redirects guard the JWKS request against SSRF

Exceptions

All implement Exceptions\OidcException with a short reason(): ProviderError (discovery, endpoint, token, refresh, refresh_rejected, userinfo, callback, logout_token_invalid, logout_token_replayed), SilentSignInRefused (silent_refused), StateMismatch (state), TokenRejected (401, reasons above), TooManyAttempts (429).

Testing

composer test      # pest
composer analyse   # phpstan, level max
composer format    # pint

License

MIT. See LICENSE.