NAME
Punk::Plugin::OAuth2 - social login for Punk applications
VERSION
Version 0.09
SYNOPSIS
package MyApp;
use Punk;
use Punk::Plugin::OAuth2;
plugin 'OAuth2';
session secret => secret('session_key'), expires => '7d';
oauth2 google => {
preset => 'google',
client_id => secret('oauth.google_id'),
client_secret => secret('oauth.google_secret'),
};
oauth2 github => {
preset => 'github',
client_id => secret('oauth.github_id'),
client_secret => secret('oauth.github_secret'),
};
oauth2 corp => {
issuer => 'https://idp.corp.example',
discovery => 1,
client_id => '...',
client_secret => '...',
};
oauth2_login '/auth' => {
on_login => 'Auth#on_login',
base_url => 'https://app.example.com',
};
package MyApp::Controller::Auth;
sub on_login {
my ($c, $identity, $tokens) = @_;
$c->session->{user} = { id => find_user($identity)->id };
return; # falls through to the post-login redirect
}
DESCRIPTION
OAuth2 and OpenID Connect for Punk. The plugin installs three keywords covering both sides of the protocol:
oauth2+oauth2_login- the client (social login): authorization-code flow with PKCE (S256 only), single-use signed state, OIDC nonce, id_token verification through Crypt::JWS and a cached JWKS, and normalized identities across providers.oauth2_server- a full authorization server and OpenID Provider (see Punk::OAuth2::Server).
For the resource-server side (validating incoming Bearer tokens as route guards or in an OpenAPI security map) see Punk::OAuth2::Checker.
Declaring a provider records configuration; plugin 'OAuth2' builds providers and mounts routes - either ordering of keyword and plugin works, and mismatches croak at to_app.
oauth2_login '/auth' mounts GET /auth/:provider (starts a login) and GET /auth/:provider/callback (completes it). Flow state lives in the signed session - at most three concurrent login attempts, each valid for ten minutes, deleted on use. Tokens are handed to on_login and then discarded: nothing token-shaped is ever stored in the session.
KEYWORDS
oauth2 NAME => \%config
Declares a provider. preset is google, github, or oidc; every preset field can be overridden. Without a preset, set issuer plus discovery => 1 (endpoints from the OIDC discovery document, issuer-checked and SSRF-guarded) or explicit authorization_endpoint/token_endpoint. Other options:
- client_id / client_secret
-
The registration with the provider.
client_secretmay be omitted for a public client (public => 1) - PKCE still applies. - scope
-
Space-separated scope string; presets carry sensible defaults.
- auth_method
-
basic(default) orbody- how client credentials reach the token endpoint. - algs
-
id_token signature allowlist, default
['RS256', 'ES256']. - allow_local
-
Relax the SSRF guard for loopback IdPs (development and tests).
- ua
-
A Fetch-compatible agent or a coderef returning one - the test seam; defaults to
$c->ua.
oauth2_login PATH => \%options
Mounts the login routes. Options:
- on_login (required)
-
Coderef or
'Controller#method', called as($c, $identity, $tokens)after a verified login.$identityis{ provider, sub, email, email_verified, name, picture, raw };$tokensis a Punk::OAuth2::Tokens. A returned reference becomes the response; otherwise the user is redirected to the flow'sreturndestination orredirect_ok. - base_url
-
The application's external origin, used to build exact redirect URIs. Required in production;
trust_proxy => 1derives it from X-Forwarded-Proto/Host instead when running behind a trusted proxy. - redirect_ok
-
Default post-login destination (
/). A?return=parameter on the initiation URL overrides it when it is a same-origin relative path - absolute and protocol-relative destinations are ignored. - on_error
-
Optional handler for failed logins; the default is a plain 400 page. Details go to the log, never the browser.
oauth2_server PATH => \%options
Mounts an OAuth2 / OpenID Connect authorization server at PATH: the authorize (GET and POST), token, revoke, introspect, register, userinfo (GET and POST), logout (GET and POST, with a logout hook), device_authorization and device (with the device option) and jwks.json endpoints, plus the RFC 8414 metadata at /.well-known/oauth-authorization-server and /.well-known/openid-configuration (registered at the app root). The token, revoke, introspect, register and device_authorization POSTs and userinfo read no cookies and are exempted from the application's csrf, whichever order csrf and oauth2_server are declared in; the exemptions are added to the application's own list, whose other settings are left alone. authorize, logout and device are not exempt: with csrf on, a POST to any of them needs the token, because they are where the user approves a client, confirms a logout, and approves a device. See "authorize" in Punk::OAuth2::Server.
oauth2_server '/oauth' => {
issuer => 'https://idp.example.com',
store => { dsn => 'dbi:SQLite:idp.db' },
authenticate => 'Auth#require_user',
consent => 'Auth#consent',
};
Grants: authorization code with PKCE (S256 only), refresh_token (with rotation and family revocation on reuse), client_credentials, and the device authorization grant with the device option. Access tokens are ES256 JWTs by default; a code issued for openid also yields an id_token. See Punk::OAuth2::Server for the full behaviour. Options:
- issuer (required)
-
The issuer URL; it appears in tokens and metadata and must match what resource servers expect.
- store (required)
-
A Punk::OAuth2::Server::Store, a
{ dsn =... }> hashref (built into one for you), or any object satisfying the store contract - see "CREATING YOUR OWN STORE" in Punk::OAuth2::Server::Store. - authenticate (required)
-
Coderef or
'Controller#method', called as($c, \%request); returns the authenticated user id (orPunk::OAuth2::Server->authenticated($id, auth_time => ..., acr => ...)), or a reference (a login redirect) that short-circuits the authorization request.\%requestcarries the client'sprompt,max_age,auth_after,acr_valuesandlogin_hint; see "authenticate" in Punk::OAuth2::Server.sub require_user { my ($c) = @_; return $c->session->{user_id} if $c->session->{user_id}; return $c->redirect('/login?to=' . ...); # a reference wins } - consent
-
Optional. Called as
($c, $client, \@scopes, \@granted); returns 1 (approve), 0 (deny), or a reference (render a consent page). Consent is by scope: approvals are recorded, and the hook is asked again only when a request reaches past what the user approved before (\@granted). - userinfo
-
Optional. Coderef or
'Controller#method', called as($c, $client, $user_id, \@scopes); returns a hashref of OpenID Connect claims about the user for theid_tokenand/userinfo. Standard claims are released only for their scope (emailneeds theemailscope, and so on). See "userinfo" in Punk::OAuth2::Server.sub userinfo { 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->verified }; } - oidc
-
OpenID Connect is on by default: a code issued for the
openidscope is also redeemed for anid_token, and/userinfois mounted.oidc => 0turns both off. - logout
-
Optional. Coderef or
'Controller#method', called as($c, $request)when a relying party sends the user to log out of this server too (OpenID Connect RP-initiated logout). Log the user out and return true, return false to leave them logged in, or return a reference - a "log out here too?" page - which the specification requires unless$request->hint_matches($current_user). Mounts/logoutand advertises theend_session_endpoint. See "RP-INITIATED LOGOUT" in Punk::OAuth2::Server. - device
-
The device authorization grant (RFC 8628), for devices with no browser:
device => 1, ordevice => { page => 'Device#page', ... }. User-code attempts are limited by Punk's rate limiter, which needs Hyperman; elsewhere the verification page refuses codes unless you giverate_limit => sub { ... }.pageandrate_limitmay be'Controller#method'. See "DEVICE AUTHORIZATION" in Punk::OAuth2::Server. - pairwise_salt, max_age_leeway, acr_values_supported
-
OpenID Connect's pairwise subject key (16 bytes or more), the grace on
max_ageandprompt=login(default 60 seconds), and theacrvalues to advertise. See "OPENID CONNECT AUTHENTICATION" in Punk::OAuth2::Server. - alg, at_ttl, rt_ttl, key
-
Signing algorithm (default
ES256), access- and refresh-token lifetimes (seconds), and an explicit signing key (a Crypt::JWS::Key; one is generated otherwise).oauth2_server '/oauth' => { issuer => ..., store => ..., authenticate => ..., alg => 'ES256', at_ttl => 600, rt_ttl => 30 * 86400, };
Both keyword and plugin orderings work, and inline declaration via plugin 'OAuth2' => { server => {...} } is equivalent to the keyword.
CONTEXT HELPERS
The plugin installs these on the context for use inside handlers.
oauth2_authurl
get '/signin' => sub {
my ($c) = @_;
my $url = $c->oauth2_authurl('google', return_to => '/dashboard');
return $c->render(template => 'signin', google_url => $url);
};
Builds the authorization URL for a provider (for hand-rolled sign-in buttons) and records the login flow in the session, so its callback can complete just like oauth2_login's own route. return_to is an optional post-login destination.
oauth2_refresh
my $fresh = $c->oauth2_refresh('google', $tokens);
# or with a raw refresh-token string:
my $fresh = $c->oauth2_refresh('google', $refresh_token);
Performs a refresh-token grant against the provider and returns a fresh Punk::OAuth2::Tokens.
oauth2_provider
my $provider = $c->oauth2_provider('google');
my $url = $provider->authorize_url(...);
Returns the configured Punk::OAuth2::Provider object for advanced use.
SECURITY NOTES
PKCE is always on and S256 only. State is 256 random bits, single-use, ten-minute lifetime. The OIDC nonce is checked against the id_token in constant time. id_token verification enforces the algorithm allowlist, issuer equality, audience (and azp with multiple audiences), and expiry with 60 seconds of leeway. Discovery and JWKS URLs must be https and resolve to public addresses unless allow_local is set. The ?return= destination is constrained to same-origin relative paths. Provider tokens are never written to the session.
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)