NAME

Punk::OAuth2::Server - an OAuth2/OIDC authorization server

SYNOPSIS

oauth2_server '/oauth' => {
	issuer  => 'https://idp.example.com',
	store   => { dsn => 'dbi:SQLite:idp.db' },
	authenticate => 'Auth#require_user',
	consent      => 'Auth#consent',
	userinfo     => 'Auth#userinfo',   # OpenID Connect claims
	logout       => 'Auth#logout',     # RP-initiated logout
};

DESCRIPTION

The other half of the distribution. Where Punk::OAuth2::Provider logs your users in somewhere else, this issues the tokens: an OAuth2 authorization server with OpenID Connect flavouring, implemented in XS, mounted by the oauth2_server keyword.

It serves /authorize, /token, /revoke, /introspect, /jwks.json, /register, /userinfo, /logout, /device_authorization, /device and the RFC 8414 / OpenID Connect discovery documents. You supply two hooks - how to authenticate a user and, optionally, how to ask them for consent - plus a store, and for OpenID Connect a third that says what to tell a client about the user. Everything else, the whole protocol, is here.

OpenID Connect is the authorization code flow with one more scope: a code issued for openid is redeemed for an id_token as well as an access token, and that access token reads the user's claims back from /userinfo. See "ID TOKENS" and "userinfo".

Supported grants are authorization code with PKCE, refresh_token with rotation, client_credentials, and - with the device option - the device authorization grant (RFC 8628) for devices with no browser. There is no implicit grant and no resource owner password grant, and they are not configurable off or on: both are removed in OAuth 2.1, and a server that cannot perform them cannot be talked into performing them.

Access tokens are JWTs (RFC 9068 at+jwt) signed with ES256 by default, so a resource server validates them statelessly with Punk::OAuth2::Checker and never calls back here. Refresh tokens, authorization codes and client secrets are opaque random strings, and the store only ever holds their SHA-256 digests.

CONSTRUCTOR

new

my $server = Punk::OAuth2::Server->new(%opts);

Usually called for you by oauth2_server. An odd number of options croaks.

issuer (required)

The issuer URL. It goes in the iss of every access token and in the metadata, and it is what a resource server checks, so it has to be the URL clients actually reach.

It is also the aud of a token requested without an RFC 8707 resource. When a resource is requested, the audience is that resource instead, which is what lets one resource server refuse a token minted for another.

store (required)

Where codes, refresh tokens, clients and consents live. A Punk::OAuth2::Server::Store, a { dsn => ... } hashref, or any object implementing the same methods. See "THE STORE".

authenticate

Coderef or 'Controller#method', called as ($c, \%request). Returns one of:

  • the authenticated user id;

  • Punk::OAuth2::Server->authenticated($user_id, auth_time => $t, acr => $acr), the user id with when and how they logged in (see "authenticated");

  • a reference - typically a redirect to your login page - which is returned to the browser as-is (or, under prompt=none, turned into a login_required error for the client);

  • false, which denies the authorization.

Required in practice: /authorize answers 500 without it.

\%request describes what the client asked of the authentication:

client_id    the client
scopes       [ the requested scopes ]
prompt       [ the prompt values: none, login, consent, ... ]
max_age      seconds, when the client sent one
auth_after   epoch seconds: the earliest acceptable login time,
             when max_age or prompt=login asked for a recent one
acr_values   [ the requested authentication context classes ]
login_hint   the client's hint about who is logging in

The one that matters is auth_after. When it is present, a user whose login is older must be sent to log in again, and the hook must report the new login's auth_time: the server refuses the request with login_required if the reported auth_time is missing or earlier. See "OPENID CONNECT AUTHENTICATION".

sub require_user {
	my ($c, $request) = @_;
	my $s = $c->session;
	my $fresh = !defined $request->{auth_after}
	         || ($s->{auth_time} // 0) >= $request->{auth_after};
	return Punk::OAuth2::Server->authenticated($s->{user_id},
	           auth_time => $s->{auth_time})
		if $s->{user_id} && $fresh;
	return $c->redirect('/login?to=' . ...);
}

Optional. Called as ($c, $client, \@scopes, \@granted) with the client row, the requested scopes split on spaces, and the scopes this user has approved for this client before. Return true to approve, false to deny, or a reference to render a consent page.

Consent is by scope. An approval is recorded as the set of scopes approved, added to any approved before, and the hook is asked again whenever a request reaches past that set - approving openid does not approve openid email later. \@granted is there so a consent page can show only what is new. A request inside the approved set is not asked again, unless it carries prompt=consent. Under prompt=none a reference is not rendered: the client gets consent_required.

If your consent page posts back to /authorize, the authenticate hook runs again on that post before consent does; see "OPENID CONNECT AUTHENTICATION" for what that means for max_age_leeway.

claims

Optional. Called as ($c, $client, $user_id, \@scopes) at /authorize, after the user has been authenticated and has consented. Return a hashref of private claims to add to the access token, or false for none.

claims => sub {
	my ($c, $client, $user_id, $scopes) = @_;
	return { acme_project => $c->session->{project} };
},

It runs once, where the user and the client are both known and the user has just approved, and what it returns is bound to the authorization code - so a token minted from that code carries what was approved, a refresh carries it forward unchanged, and the token request cannot influence it. A request is the client talking; a claim it could set would be a claim the user never agreed to.

A private claim never overwrites a registered one. iss, sub, aud, exp, iat, jti, client_id and scope are the protocol's, and a hook that could move any of them would be a way around the audience and expiry checks rather than an addition to them.

userinfo

Optional. OpenID Connect's claims about the user. Called as ($c, $client, $user_id, \@scopes) and returns a hashref of claims, or false for none:

userinfo => sub {
	my ($c, $client, $user_id, $scopes) = @_;
	my $u = MyApp::User->find($user_id) or return;
	return {
		name           => $u->name,
		email          => $u->email,
		email_verified => $u->email_confirmed,
	};
},

It runs when a code issued for openid is redeemed at /token, for the id_token, and at each /userinfo request. Both of those are the client's request, not the user's browser, so $c has no session for the user: look them up by $user_id.

The hook is given the granted scopes and should honour them, and the server holds it to that. A standard claim (OIDC Core 5.4) is only passed when its scope was granted: name, picture, locale and the rest of the profile claims need profile; email and email_verified need email; address needs address; phone_number and phone_number_verified need phone. Returning the whole user record therefore cannot leak an email address to a client that was granted openid profile. A claim that is not a standard one is the application's, and is passed as returned.

Protocol claims are never the hook's: sub, iss, aud, nonce, exp and the like are dropped from what it returns. sub is always the user id the token was issued for, so the id_token and userinfo answers cannot disagree about who the user is. email_verified and phone_number_verified are sent as JSON booleans whatever truthy value the hook uses.

If the hook dies, the request fails with 500 server_error and the error is warned. At /token that means the code has been spent and the client starts again, which is deliberate: an identity issued with the profile silently missing is worse than a failed login.

Without this hook, id_tokens and /userinfo still work and carry only sub.

logout

Optional. OpenID Connect RP-initiated logout: called as ($c, $request) at /logout, where a relying party sends the user to log out of this server as well. The server holds no session, so this hook is what logs the user out. Return a reference to send a page (usually "log out here too?"), true once the user is logged out, or false if they are not. Without it, /logout is not mounted and no end_session_endpoint is advertised. See "RP-INITIATED LOGOUT".

device

The device authorization grant (RFC 8628): device => 1, or a hashref of

page        a hook rendering the verification page, ($c, \%info);
            a plain built-in page otherwise
expires_in  seconds a device code lives, default 600
interval    seconds between polls, default 5
attempts    user-code attempts per expires_in, per client address
            and per user, default 5
rate_limit  a limiter of your own, ($c, $key, $limit, $window),
            returning true to allow; Punk's rate limiter otherwise

Mounts /device_authorization and /device. The store must implement the device methods ("device_put" in Punk::OAuth2::Server::Store), and an unknown key croaks - a misspelt rate_limit is otherwise a limiter that is not there. See "DEVICE AUTHORIZATION".

key

The signing key, a Crypt::JWS::Key. One is generated for alg if you do not supply one, which is fine for a single process and wrong for anything that restarts or runs more than one worker - see "THE SIGNING KEY".

alg

Signing algorithm for access tokens and id_tokens. Default ES256.

OpenID Connect Discovery says an OpenID Provider must support RS256, and some relying parties accept nothing else. If yours are among them, configure alg => 'RS256' with an RSA key.

at_ttl

Access token lifetime in seconds. Default 600.

rt_ttl

Refresh token lifetime in seconds. Default 2592000 (30 days).

prefix

Path the endpoints are mounted under, used to build the metadata URLs. Default /oauth.

pairwise_salt

The key for pairwise subject identifiers, at least 16 bytes; a shorter one croaks. Keep it secret and never change it: it is what every pairwise sub is computed from, so a new one changes every pairwise user's identifier at every client that uses them. Without it, pairwise clients are refused (server_error at /authorize) and only public is advertised. See "Pairwise subject identifiers".

max_age_leeway

Seconds of grace on max_age and prompt=login, default 60. It is what lets a login that has just happened count as fresh when the user arrives back at /authorize a few seconds later. See "OPENID CONNECT AUTHENTICATION".

acr_values_supported

The authentication context classes to advertise in the discovery document, as an arrayref or a space-separated string. Advertised only; what is achieved is what your authenticate hook reports.

oidc

OpenID Connect, on unless this is given and false. With oidc => 0 the openid scope means nothing special: no id_token is issued, /userinfo is not mounted and answers 404, the discovery documents do not advertise it, and client_credentials may carry openid like any other registered scope.

ENDPOINTS

Each takes the Punk context and returns a PSGI triplet, so they can be mounted as routes directly, which is what oauth2_server does. Every JSON response carries Cache-Control: no-store and Pragma: no-cache.

authorize

$server->authorize($c);

The authorization endpoint. Its parameters are response_type, client_id, redirect_uri, state, scope, nonce, code_challenge, code_challenge_method and the repeatable resource.

They are read from the query string of a GET. A POST is read from the application/x-www-form-urlencoded body (OIDC Core 3.1.2.1) and the query string, so a consent page that posts back to /authorize?<the original query> with only its own fields in the body keeps working. A parameter may appear once: sent twice in one place, or in both places with different values, the request is answered 400 and not redirected (RFC 6749 3.1). Choosing one of the two would let whoever wrote the other pick the client, the redirect URI or the PKCE challenge. The same value in both places counts as once. resource values from both places are collected.

If your authenticate hook bounces the user to a login page, remember that a POSTed request's parameters are in the body and the login redirect can only carry a URL back: fold them into the return URL, as example/oauth-server.psgi does, or the user returns to an empty request. And if the application enables Punk's csrf, a POST here is checked like any other: the plugin does not exempt this route, because it is also where a consent page posts its approval, and an exemption would let another site submit that approval for the user. An RP that form-POSTs its authorization request cross-site is refused unless the application exempts the route and makes its consent hook check its own CSRF token.

What it does, in order, and the order is the point:

  1. Look up client_id, and match redirect_uri exactly against that client's registered set. Both are required. Failures here answer 400 text/plain and do not redirect - with an unverified redirect target there is nowhere safe to send an error, and redirecting anyway is how an authorization server becomes an open redirector.

  2. Require response_type=code and PKCE with code_challenge_method=S256. From here the redirect target is trusted, so these answer by redirecting back with error and state (unsupported_response_type and invalid_request respectively). S256 is the only accepted method: plain is not implemented, so it cannot be downgraded to.

  3. Check the request against the client's registration: the client must be registered for the authorization_code grant (unauthorized_client), and every scope in scope must be one of its registered scopes (invalid_scope). Both redirect back with the error. See "WHAT A CLIENT MAY ASK FOR".

  4. Check the OpenID Connect parameters: prompt=none combined with another value, or a max_age that is not a whole number of seconds, is invalid_request. A client whose subject cannot be computed (pairwise with no pairwise_salt, or with no sector) is server_error, before the user is asked to log in.

  5. Call authenticate. A reference is returned to the browser unchanged, which is how you send the user to a login page - except under prompt=none, where it becomes login_required. A false return redirects back with access_denied. When the request asked for a recent login (max_age, prompt=login), an auth_time that is missing or too old is login_required.

  6. Call consent, unless the user has already approved every requested scope for this client (and the request is not prompt=consent). A reference renders your consent page (consent_required under prompt=none); a false return is access_denied; a true return adds the scopes to what is recorded.

  7. Mint a 32-byte random code bound to the client, user, redirect URI, scope, nonce, challenge, auth_time and acr, valid for ten minutes, and redirect back with code, state and iss.

The iss parameter on the response is RFC 9207, and lets a client detect a mix-up between two authorization servers.

token

$server->token($c);

The token endpoint. Parses an application/x-www-form-urlencoded body and authenticates the client (see "CLIENT AUTHENTICATION") before looking at the grant; an unauthenticated client is 401 invalid_client whatever it asked for.

The named grant must then be one the client is registered for, or it is 400 unauthorized_client before any arm runs - the grant type is a field in a body the client wrote, so it says what the client wants, not what it may have. See "WHAT A CLIENT MAY ASK FOR".

authorization_code

Consumes the code, which is single-use - the store deletes it on read, so a replay finds nothing. Then it checks that the code was issued to this client, has not expired, and was issued for exactly this redirect_uri, and that S256 of the supplied code_verifier equals the stored challenge, compared in constant time. Any failure is invalid_grant with no detail: a client that guessed wrong learns only that it was wrong.

Returns an access token and a refresh token, and an id_token when the code was issued for the openid scope (see "ID TOKENS").

refresh_token

Checks the token belongs to this client, is not revoked, and has not expired, then rotates it: a new refresh token is issued in the same family and the old one is marked as consumed.

If the presented token was already rotated, that is treated as theft rather than as a mistake - the legitimate client would be holding the new token - and the entire family is revoked, logging out the attacker and the victim together. The response is still a bare invalid_grant.

client_credentials

No user, no refresh token. The access token's sub is the client id.

Confidential clients only: a public client is 401 invalid_client here, because it authenticates on nothing but an identifier. The requested scope must be registered to the client, or the request is invalid_scope.

openid is invalid_scope here even when it is registered: it asks for an end-user's identity and this grant has none. It is refused rather than ignored because it is the scope /userinfo admits a token on.

urn:ietf:params:oauth:grant-type:device_code

With the device option: a device polling for the outcome of its authorization. See "Polling".

Anything else is unsupported_grant_type.

revoke

$server->revoke($c);

RFC 7009. Client-authenticated, and always answers 200 with an empty object - revoking an unknown or already-dead token is indistinguishable from revoking a live one, so the endpoint cannot be used to probe which tokens exist. Revoking a refresh token kills its whole rotation family.

introspect

$server->introspect($c);

RFC 7662. Client-authenticated. An access token is verified locally against this server's own key and algorithm; a refresh token is looked up in the store and must be unrevoked, unrotated and unexpired.

Only this server's access tokens (typ at+jwt) and refresh tokens are ever active. An id_token is signed by the same key and is not one: it introspects as inactive, so a resource server behind the introspection checker cannot be handed one in place of an access token.

A live token answers with active true plus sub, scope, client_id and exp as available. Everything else - malformed, expired, revoked, never issued - answers with exactly {"active":false}, so nothing about a token can be learned from how it is refused.

userinfo

GET  /oauth/userinfo
POST /oauth/userinfo
Authorization: Bearer <access token>

The OpenID Connect UserInfo endpoint (OIDC Core 5.3): the user's claims, as JSON, for an access token issued with the openid scope. The token goes in the Authorization header; it is not read from a form body or the query string.

The token must be this server's access token (typ at+jwt, so an id_token is refused), unexpired, audienced for this issuer, and its client must still be registered. A token minted for an RFC 8707 resource belongs to that resource server and is refused here. Failures are RFC 6750 challenges: 401 with a bare WWW-Authenticate when no token was sent, 401 invalid_token for a token that fails any of those checks, and 403 insufficient_scope (naming openid) for a good token without openid.

The answer is the sub the id_token carried - the user id, or the pairwise identifier for a pairwise client - plus whatever the userinfo hook releases for the token's scopes. The hook is given the user id. Not mounted when oidc => 0.

logout

GET  /oauth/logout?id_token_hint=...&post_logout_redirect_uri=...&state=...
POST /oauth/logout

The OpenID Connect end_session_endpoint (RP-Initiated Logout 1.0). Mounted only with a logout hook. See "RP-INITIATED LOGOUT".

device_authorization

POST /oauth/device_authorization
client_id=tv&scope=openid+read

RFC 8628 section 3.1: a device asks to be authorized. Client-authenticated like /token (a public client by client_id alone), and held to the registration: the client must be registered for urn:ietf:params:oauth:grant-type:device_code (unauthorized_client), and its scope and resource must be registered (invalid_scope, invalid_target). Answers device_code, user_code, verification_uri, verification_uri_complete, expires_in and interval. Mounted with the device option; csrf exempt.

device

GET  /oauth/device
GET  /oauth/device?user_code=BCDF-GHJK
POST /oauth/device

The verification page, where the user enters the code their device shows and allows or denies it. See "DEVICE AUTHORIZATION". Mounted with the device option; not csrf exempt.

jwks

$server->jwks($c);

The public half of the signing key as a JWKS document, with kid, use => 'sig' and alg set. This is what resource servers fetch to validate access tokens.

metadata

$server->metadata($c);

The RFC 8414 authorization server metadata: the issuer, the endpoint URLs built from the issuer and prefix (including the registration_endpoint, which is how a client with no client_id finds its way to one), and the supported grant types, response types, PKCE methods and signing algorithms. With the device option it carries the device_authorization_endpoint and the device grant among grant_types_supported. With OpenID Connect on it also carries the userinfo_endpoint, the end_session_endpoint when a logout hook is configured, subject_types_supported (public, and pairwise when a pairwise_salt is configured), claims_supported (the claims the server itself issues), acr_values_supported when configured, and scopes_supported, which names only openid - which other scopes exist is the application's business. The plugin serves it at both /.well-known/oauth-authorization-server and /.well-known/openid-configuration.

register

POST /oauth/register

RFC 7591 dynamic client registration, for a client that has no client_id and no way of being handed one out of band. That is how a connector living inside somebody else's product reaches a server nobody configured it for.

Takes a JSON body with redirect_uris (required), and optionally client_name, scope, subject_type (public, the default, or pairwise) and post_logout_redirect_uris (held to the same rule as redirect_uris). Answers 201 with the issued client_id.

A pairwise client registered here is sectored by its redirect URIs' host, so they must all share one, and the server must have a pairwise_salt. sector_identifier_uri is refused with invalid_client_metadata: the specification has the server fetch it and check that it lists every redirect URI, which this server does not do, and trusting one unchecked from an open endpoint would let a client claim another RP's sector and be told that RP's pairwise subjects. An administrator can set a sector_identifier on a client through the store instead.

What it creates is deliberately narrow. The client is public and is issued no secret, because a secret handed out over an open endpoint protects nothing. It receives the authorization code and refresh grants only: client_credentials is a confidential-client grant, and granting it here would let anyone mint tokens in their own right simply by asking. Redirect URIs must be https, or plain http on localhost or 127.0.0.1, which is how a native client receives its code.

The endpoint is open by construction. Mount it behind whatever per-address quota the surrounding application already uses; this distribution does not invent one, because the application owns that policy.

prefix

The configured path prefix, defaulting to /oauth.

authenticated

return Punk::OAuth2::Server->authenticated($user_id,
	auth_time => $epoch_seconds,   # when the user logged in
	acr       => $acr,             # how, e.g. 'urn:acr:mfa'
);

What an authenticate hook returns when it has more to say than the user id. Both keys are optional; auth_time is needed whenever the request asked for a recent login. Croaks on a missing user id, an unknown key, an auth_time that is not epoch seconds, or an empty acr.

It is an object rather than a hashref because a hashref returned from a Punk handler is already a response (rendered as JSON), and a reference from authenticate means "send this to the browser".

ACCESS TOKENS

Access tokens are signed JWTs with typ at+jwt (RFC 9068) and the kid of the signing key, carrying:

iss        the issuer
sub        the user id, or the client id for client_credentials
aud        the issuer, or the RFC 8707 resource(s) requested
client_id  the client the token was issued to
exp / iat  from at_ttl
jti        a random 16-byte identifier
scope      when the grant carried one

plus any private claims from the claims hook, which never replace these.

Because they are verifiable offline, a resource server never talks to this one on the request path, and the cost of that is the usual one: a token stays valid until it expires. Keep at_ttl short - the default is ten minutes - and let the refresh token carry the long-lived authority, where it can be revoked.

ID TOKENS

A code issued for a scope that includes openid is redeemed for an id_token alongside the access and refresh tokens. It is a JWT signed with the same key and alg, published at /jwks.json, with typ JWT in its header, carrying:

iss        the issuer
sub        the user id as a string - or, for a pairwise client,
           its pairwise identifier for the user
aud        the client_id, and nothing else
exp / iat  from at_ttl
auth_time  when the user logged in, when the authenticate hook
           reported it (always, when max_age was requested)
acr        the authentication context class the hook reported
nonce      the nonce sent to /authorize, when one was
at_hash    binds it to the access token issued with it

plus the claims the userinfo hook releases for the granted scopes.

Its audience is the client alone because an id_token says who logged in to that client; it is not a credential for anything. The access token that comes with it is, and the two cannot be swapped: an id_token is refused at /userinfo, introspects as inactive, and (with its aud being a client id) is refused by Punk::OAuth2::Checker, whose JWT checker requires an audience for exactly this reason.

A refresh does not issue a new id_token. It carries openid forward, so the refreshed access token still reaches /userinfo.

OPENID CONNECT AUTHENTICATION

The server keeps no session: whether a user is logged in, and since when, is the application's knowledge, reached through the authenticate hook. So the authentication request parameters are honoured by telling the hook what the client asked for and checking what it answers.

prompt

none asks for no user interface at all, for a silent check of an existing login. A reference from authenticate (a login page) becomes login_required, and one from consent (a consent page) becomes consent_required, both sent to the client's redirect_uri with the state. A hook that answers without a page - a logged-in user, a consent that auto-approves - answers as usual. none with any other value is invalid_request.

login asks for a fresh login; it is treated as max_age=0, which is what OpenID Connect makes it equivalent to. consent asks the consent hook even when the scopes were approved before. Every value, select_account and any this server does not know included, is passed to the hook in $request->{prompt}.

max_age and auth_time

max_age asks for a login no older than that many seconds. The hook is given auth_after, the earliest acceptable login time (now - max_age - max_age_leeway), must send an older login back through the login page, and must report the login time with Punk::OAuth2::Server->authenticated($user, auth_time => $t). A missing or earlier auth_time is refused with login_required (and warned, outside prompt=none, because it means the hook ignored the request): an id_token claiming an authentication the client did not get would be worse than none.

auth_time goes in the id_token whenever the hook reports it.

The leeway is there because a login that has just happened is a few seconds old by the time the user is back at /authorize. It also has to cover a consent page: if the page posts back to /authorize, the authenticate hook runs again on that post, and a user who spent longer than the leeway reading it is sent to log in again. With a short max_age and a consent page, raise max_age_leeway.

acr

acr_values is passed to the hook as $request->{acr_values}; the class the hook reports with authenticated(..., acr => $acr) goes in the id_token as acr. The server does not check one against the other: acr_values is a request, and what was achieved is the hook's to say. acr_values_supported only advertises.

Pairwise subject identifiers

A client registered with subject_type => 'pairwise' is not told the user id. It is told

base64url(HMAC-SHA256(pairwise_salt, sector . "\0" . user_id))

in the id_token and at /userinfo, so two clients in different sectors cannot tell that they share a user. The sector is the client's sector_identifier - a host, or a URL whose host is taken - or else the host its redirect_uris share; a pairwise client whose redirect URIs span hosts and that has no sector_identifier is refused. Clients in one sector see the same identifier, which is what lets one relying party run on several hosts.

An unknown subject_type is refused rather than treated as public, since the failure it would cause - every client told the same identifier - is the one a pairwise client registered to avoid.

The userinfo and claims hooks are still given the real user id, and so are resource servers: the access token's sub is the user id, as RFC 9068 expects of a token a resource server correlates with its own data. The access token is a JWT, so a client that decodes it - which RFC 9068 says clients must not do - can read that id. Pairwise identifiers stop correlation through what the client is given as identity; they do not make the access token opaque.

RP-INITIATED LOGOUT

A relying party that logs a user out of itself can send them to /logout to log out of this server too (OpenID Connect RP-Initiated Logout 1.0). Its parameters, by GET or form POST, read as /authorize's are (a parameter sent twice is refused):

id_token_hint             an id_token this server issued to the RP
client_id                 the RP
post_logout_redirect_uri  where to send the user afterwards
state                     passed back on that redirect
logout_hint, ui_locales   passed to the hook

The server decides what the request proves and where the user may go; the logout hook decides whether, and does, the logging out.

What the server checks

The id_token_hint must be an id_token this server signed: its key, its alg, typ JWT (an access token is not a hint) and its issuer. Its expiry is not checked - the specification asks for an expired hint to be accepted, because an RP logs a user out long after the id_token it holds expired. A hint that fails these checks is ignored rather than refused, so a token signed by a key since rotated still lets the user log out; it just cannot send them anywhere.

A client_id that the hint was not issued to is a 400, and so is an unknown client_id, and neither reaches the hook. Without a client_id, the client is the one the hint was issued to.

The user is redirected to post_logout_redirect_uri afterwards - with state added - only when there is a valid hint and the URI exactly matches one of that client's registered post_logout_redirect_uris. Anything less is not an error, because the user still wants to log out: there is simply no redirect, and the server answers with a plain "You have been logged out." page. This is what keeps the endpoint from being an open redirector anyone can link to.

The hook

$request is a Punk::OAuth2::Server::LogoutRequest: a hash of

client_id    the RP, named or from the hint
client       its client row
subject      the hint's sub - what the RP was told; only with a
             valid hint
state, logout_hint, ui_locales
redirect     where the user will be sent if the hook returns true,
             state included; absent when there will be no redirect

and one method:

hint_matches

$request->hint_matches($user_id)

True when the id_token_hint names that user; false for another user, or when there was no valid hint. Use it rather than comparing subject yourself: for a pairwise client the subject is not the user id, and hint_matches computes what that client was told for the user you name, comparing in constant time.

Asking the user

The specification says the user must be asked before being logged out unless the hint names the logged-in user - otherwise any page can log your users out with a link. So the hook should look like this:

sub logout {
	my ($c, $request) = @_;
	my $user = $c->session->{user_id};
	my $confirmed = $c->req->method eq 'POST'
	             && ($c->req->form->{confirm} // '') eq 'yes';
	return $c->render('confirm_logout', { ... })   # posts back here
		if $user && !$request->hint_matches($user) && !$confirmed;
	$c->session_expire;
	return 1;
}

The confirmation page posts back to /logout with the request's own parameters (as hidden fields, or in the action's query string) and its answer, so the redirect to the RP still happens after a "yes". With Punk's csrf on, that post needs the CSRF token: /logout is deliberately not exempt, since an exemption would let another site submit the "yes". example/oauth-server.psgi has a complete hook.

The return value: a reference is sent as it is; true means logged out, and the server redirects or answers "You have been logged out."; false means not logged out, and the server answers "You have not been logged out." without redirecting to the RP. If the hook dies, the answer is 500 and the error is warned.

What logging out does not do

It ends what your hook ends - the user's session with this server. It does not revoke refresh tokens already issued, which are the client's and live until revoked at /revoke or expired; and it does not tell other RPs the user has gone (front-channel and back-channel logout are not implemented).

DEVICE AUTHORIZATION

RFC 8628, for a device that has no browser, or no keyboard worth using: a TV, a games console, a command-line tool. The device asks for a code, shows the user a short user_code and a URL, and polls /token while the user approves it on a phone or a computer.

The codes

The device_code is 32 random bytes and is the device's secret. The user_code is what a person types: eight letters from twenty consonants, shown as XXXX-XXXX - no vowels, so no code spells a word, and none of 0/O or 1/I to misread. It is accepted in any case, with or without the dash. Both are stored as digests, like every other credential here.

Eight letters from twenty is about 34.6 bits. That is too little to be safe on its own, and RFC 8628 (section 5.1) does not pretend otherwise: it is safe together with a limit on attempts. So the limit is not optional.

The attempt limit

Every lookup of a code at /device is counted, before the code is looked up, against the client's address and against the logged-in user: by default 5 per expires_in (600 seconds) each. Past either, the page answers 429 and looks nothing up - not even a code that is right, because counting only the failures would let the guess that happens to be right through however many came before it.

The counting is Punk's rate limiter, $c->rate_hit (Punk::RateLimit), whose counters live in Hyperman's shared arena and so are exact across all of a server's workers. That limiter fails open by design: with no Hyperman arena under the application - plackup, Starman, a test harness - it allows everything. For the user code that would mean unlimited guessing, so this server checks: once per worker it hits a throwaway key twice with a limit of one, and an enforcing limiter refuses the second. If the limiter is not enforcing, /device refuses to look codes up (503, and a warning), and checks again a minute later.

So: run under Hyperman, or give device => { rate_limit => sub {...} } - a limiter of your own, over Redis, say - called as ($c, $key, $limit, $window) and returning true to allow. A rate_limit that dies refuses.

Behind a reverse proxy, declare Punk's proxy, or every user shares the proxy's address and one bucket; see "BEHIND A REVERSE PROXY" in Punk::RateLimit.

The verification page

The user must be logged in first - the authenticate hook runs as at /authorize, with $request->{device} set - so guessing codes at all takes an account, and attempts can be counted per user. A redirect from the hook is sent as it is, and the login page's return URL should bring the user back with the code.

A code that is found is confirmed, not approved. The page names the client and the scopes, shows the code, and asks the user to check it against their device before choosing (RFC 8628 section 5.4: a user sent a code by someone else should notice it is not theirs). The choice is a POST carrying a confirmation the server signed for this user and this device authorization, ten minutes long. A link - even verification_uri_complete, even with decision=approve on it - only ever shows the confirmation. Without that, anyone could send a logged-in user a link that approves the attacker's device with the user's account.

The approval lands only while the authorization is still pending, so one code cannot be approved twice, or by two users at once. The claims hook runs at approval, as it does at /authorize; the consent hook does not - the confirmation is the consent, and it is asked every time.

The built-in page is plain HTML. It is sent with X-Frame-Options: DENY and frame-ancestors 'none', since a page whose button approves a device must not be framed and clicked through, and it carries the application's CSRF token when Punk's csrf is on. A page hook replaces it, called as ($c, \%info):

stage        'enter', 'confirm' or 'done'
error        invalid_code, expired_code, slow_down, unavailable,
             invalid_confirmation or invalid_request, on 'enter'
action       the URL the forms go to
user_code    the code, XXXX-XXXX            ('confirm')
client, client_name, scopes                 ('confirm')
confirm      post this back, as `confirm`   ('confirm')
approved     true or false                  ('done')

On enter, a form sends user_code (a GET is fine). On confirm, a POST form sends user_code, confirm, and decision - approve or deny - plus your CSRF token if csrf is on. Send your page with the same anti-framing headers.

Polling

The device polls /token with grant_type=urn:ietf:params:oauth:grant-type:device_code, its device_code and its client authentication. Until it has tokens it gets a 400 with one of (section 3.5):

authorization_pending  the user has not decided yet
slow_down              it polled sooner than `interval` after its last
                       poll; the interval grows by 5 seconds, for this
                       and every later poll
access_denied          the user denied it
expired_token          the code's lifetime is over

Once approved, the next poll gets an access token, a refresh token, and an id_token when openid was asked for (with auth_time and acr from the approval, and no nonce). The device_code is single use: it is deleted before anything is minted, and only the poll whose delete removed it is answered with tokens. The client's registration is consulted again then, so a scope withdrawn meanwhile is invalid_scope.

CLIENT AUTHENTICATION

/token, /revoke and /introspect all authenticate the client first, by HTTP Basic (URL-decoded, per RFC 6749) or by client_id and client_secret in the form body. The presented secret is digested and compared against the stored digest in constant time.

A client registered with no secret is public, and authenticates on its client_id alone. That is not a weakening: a public client is one that cannot keep a secret, which is why the authorization code grant requires PKCE from everybody.

It does mean a public client is only ever as authenticated as an identifier anyone can read out of a browser, so the client_credentials grant - whose whole security is client authentication - is refused to one outright, with invalid_client (RFC 6749 section 4.4).

WHAT A CLIENT MAY ASK FOR

Three things come out of the request rather than the registration: the grant_type is a field in the token request body, and scope and resource are parameters on the authorization request. None of them is the client's to choose. All are checked against the client's own row:

  • The grant_type must be one of the client's registered grant_types, or the token endpoint answers 400 unauthorized_client. /authorize requires authorization_code the same way. Without this, a client registered for the authorization code flow alone could post grant_type=client_credentials and be handed a token of its own.

  • Every space-separated scope must be one of the client's registered scopes, or the request is invalid_scope - at /authorize, at /token for client_credentials, and again when a code or a refresh token is redeemed, so that narrowing a registration takes effect on credentials that were issued before it. A request that names no scope asks for nothing and is always allowed.

  • Every RFC 8707 resource must be one of the client's registered resources, or the request is invalid_target - at /authorize, and again at /token, where a request may narrow to a resource the code was issued for but can never reach past it. A client that registered no resources may ask for none. This is what binds a token's aud to a particular resource server instead of to the issuer, so a token minted for one is refused by another.

All three lists are deny by default, exactly as redirect_uris is: a client with no registered scopes gets no scope, one with no registered grant_types can use no grant, and one with no registered resources can name no resource. Punk::OAuth2::Server::Store defaults grant_types to authorization_code refresh_token at registration when you do not say otherwise, so the list to think about in practice is scopes.

The point of the recheck at redemption is that an access token is signed and self-contained: once one is out, the only thing standing between a scope and a resource server is what was put in the token. So the registration is consulted every time one is minted, not once when the grant began.

THE SIGNING KEY

If you do not pass key, one is generated at construction. That is convenient for a test and wrong for a deployment: a generated key does not survive a restart, so every previously issued access token becomes unverifiable, and two workers would sign with two different keys while publishing one JWKS.

Generate a key once, keep it wherever your other secrets live, and pass it in:

oauth2_server '/oauth' => {
	issuer => 'https://idp.example.com',
	key    => Crypt::JWS::Key->from_pem(secret('idp.signing_key')),
	...
};

THE STORE

The server itself holds no state. Clients, authorization codes, refresh tokens and consents all live in the store, and every credential is digested before it gets there, so a copy of the database yields no usable token.

Punk::OAuth2::Server::Store is the shipped DBI implementation. Any object providing the same methods works: client_get, code_put, code_take, refresh_put, refresh_take, refresh_rotate, refresh_revoke_family, consent_get and consent_put, and with the device option device_put, device_get, device_get_by_user_code, device_update and device_delete. Its POD documents the contract, including which of them must delete and which must not, and the client fields a store must hand back.

CAVEATS

OpenID Connect here is the authorization code flow, with prompt, max_age, auth_time, acr and pairwise subjects. Not implemented: the id_token_hint and claims request parameters (accepted and ignored), the amr and sid claims, sector_identifier_uri verification, signed or encrypted userinfo, and front-channel and back-channel logout. RP-initiated logout is implemented, but ends only what the logout hook ends; see "What logging out does not do".

SEE ALSO

Punk::Plugin::OAuth2 for the oauth2_server keyword that mounts this, Punk::OAuth2::Server::Store for the storage contract and schema, and Punk::OAuth2::Checker for the resource-server side that validates the tokens issued here.

AUTHOR

LNATION, <email at lnation.org>

LICENSE AND COPYRIGHT

This software is Copyright (c) 2026 by LNATION <email@lnation.org>.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)