Skip to content

OAuth 2.0, OpenID Connect & Single Sign-On ​

"The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf." — RFC 6749, The OAuth 2.0 Authorization Framework, Abstract (October 2012)

Summary: OAuth 2.0 is a way to hand an application a limited, revocable key to an API without handing it your password. OpenID Connect adds one thing on top: a signed statement (the ID token) that says who logged in. Single sign-on is what you get when many applications trust the same identity provider and reuse its login session. This chapter takes all three apart: roles, every grant still in use and the two that are dead, each parameter of the redirect dance, the tokens, the attacks and their fixes, logout, federation, and the products that implement them. Focus: Roles; authorization code + PKCE (code_challenge, code_verifier, S256); client credentials; the device authorization grant; refresh tokens and rotation; why the implicit and password grants are gone (RFC 9700, OAuth 2.1); redirect_uri exact matching; state, nonce, the iss response parameter; access, refresh and ID tokens; bearer usage and RFC 6750 errors; introspection and revocation; OIDC claims, UserInfo, discovery, dynamic client registration, hybrid flow, prompt, max_age, acr; RP-initiated, front-channel and back-channel logout; SSO, SAML 2.0, federation and identity brokering; the BFF pattern; PAR, JAR, mTLS, DPoP, FAPI 2.0; token exchange; multi-tenant issuers; Keycloak, Auth0, Okta, Entra ID, Cognito, Ory Hydra, Dex, Laravel Passport and Socialite; golang.org/x/oauth2 and go-oidc. Learning goal: Given an application (web, SPA, mobile, TV, service), choose the grant and the client type; draw the exact request and response of every step; list what the client must check on the callback and on the ID token; place the tokens so XSS cannot take them; design logout across several apps; and ship a Go BFF relying party, a Go resource server and a Laravel 13 Passport/Socialite setup that pass those checks.

This chapter owns the delegation and federation protocols. The token format (JWS, alg, kid, validation pitfalls) is in JWT Deep Dive; passwords, MFA and first-party sessions are in Authentication; cookie attributes, CSRF and CORS are in Web Sessions, Cookies & CORS; what a user may do once identified (roles, policies) is in Authorization Models; certificates between services are in Mutual TLS; the TLS handshake is in TLS in practice.

Page map ​

If you are looking forGo to
The whole protocol in four tablesEverything in one minute
Why passwords cannot be shared with appsWhy it exists
RFC 6749 to OAuth 2.1, OIDC, SAMLWhere it comes from
Resource owner, client, AS, RSRoles
Public vs confidential clients, client authClient types
The main flow, step by stepAuthorization code
code_challenge, code_verifier, S256PKCE
Machine-to-machine tokensClient credentials
TVs and CLIsDevice authorization grant
Long sessions, rotationRefresh tokens
Why not implicit or passwordDeprecated grants
Exact matching, open redirectorsredirect_uri
state, nonce, issState, nonce and iss
Scope vs claim vs permissionScopes
Access, refresh, ID tokens; bearerTokens
Opaque vs JWT, RFC 7662, RFC 7009Introspection and revocation
What OIDC addsID token and claims
/userinfo, .well-knownUserInfo and discovery
prompt, max_age, acr, hybridAuthentication request options
Logging out everywhereLogout
One login, many apps; SAMLSSO and federation
Tokens in a SPABFF and token storage
PAR, JAR, mTLS, DPoP, FAPIHardening the flow
Service calls on behalf of a userToken exchange
Tenants and issuersMulti-tenant identity
ProductsProducts
Parameters and error codesMechanics
CodeGo, Laravel
Production failuresSolving the classic problems
Which grant for which appChoosing
Monolith to distributed systemIn architecture
LabLab

Everything in one minute ​

The four roles (RFC 6749 section 1.1).

RolePlain wordsExample
Resource ownerThe person (or system) whose data it isAna, who has orders in the shop
ClientThe application that wants accessThe shop's web app, a mobile app, a CLI
Authorization server (AS)Issues tokens after asking the ownerKeycloak, Okta, Entra ID, Laravel Passport
Resource server (RS)The API that accepts tokensorders-api

The grants, with their 2026 status.

Grantgrant_type at /tokenWho uses itStatus
Authorization code + PKCEauthorization_codeEvery app with a user and a browserThe default; PKCE required in OAuth 2.1
Client credentialsclient_credentialsService to service, no userCurrent
Device authorizationurn:ietf:params:oauth:grant-type:device_codeTVs, CLIs, IoTCurrent (RFC 8628)
Refresh tokenrefresh_tokenAny client holding a refresh tokenCurrent; rotate or sender-constrain for public clients
Token exchangeurn:ietf:params:oauth:grant-type:token-exchangeAPIs calling APIs for a userCurrent (RFC 8693)
Implicit(none: response_type=token)Old SPAsSHOULD NOT (RFC 9700); removed in OAuth 2.1
Resource owner passwordpasswordOld first-party appsMUST NOT (RFC 9700); removed in OAuth 2.1

The three tokens.

TokenFor whomFormatLifetime (typical)Never do
Access tokenThe resource serverOpaque or JWT (at+jwt)5 to 60 minutesUse it as proof of login at the client
Refresh tokenThe authorization server onlyOpaqueHours to 90 days, rotatedSend it to an API, put it in localStorage
ID tokenThe client (relying party)Always a signed JWTMinutesSend it to an API as a bearer token

The checks a client must make on the callback.

CheckStopsWhere
state equals the value bound to this browserCSRF on the redirect endpoint, login CSRFCallback
iss equals the expected issuer (RFC 9207)Mix-up attacksCallback
PKCE code_verifier sent with the codeCode injection, stolen codesToken request (the AS checks)
ID token signature, iss, aud, expForged or misdirected tokensAfter the token response
ID token nonce equals the value sentReplayed ID tokensAfter the token response

Why it exists ​

Before OAuth, an app that wanted your photos at another site asked for your password at that site. That gave the app everything, forever, with no way to take back access without changing the password everywhere, and it trained users to type passwords into any form. OAuth replaces the password with a token that is limited (scopes, one audience), short-lived, revocable, and issued only after the owner said yes at the site that owns the account.

OAuth alone says nothing about who the user is: an access token is a key, not an identity card. Apps abused it for login anyway ("if I can read /me with this token, the user must be Ana"), which is broken because a token issued to another app can be replayed. OpenID Connect fixes that with the ID token, a signed statement addressed to one client. SSO follows: when many apps rely on one OpenID Provider, the user logs in once there and every app gets its own ID token.

ChoiceGainCost
Share the password with the appNo infrastructureFull access, no revocation, phishing training
OAuth access tokenLimited, revocable, owner consentsRedirects, an authorization server to run
Access token used as loginWorks on a demoToken substitution: any app's token logs you in
OIDC ID tokenSigned, audience-bound identityMust validate correctly (signature, aud, nonce)
One IdP for all apps (SSO)One login, central MFA, central offboardingThe IdP becomes a single point of failure and of attack

An everyday picture. A hotel. You (the resource owner) show your passport once at the front desk (the authorization server). The desk gives a key card (access token) that opens your room and the gym (scopes) until Sunday (expiry). The cleaning service (a client) asks the desk for a card for your room only, and the desk calls you first (consent). The card says nothing about who you are; the registration slip in your name, stamped by the desk and addressed to the restaurant (ID token, audience = restaurant), does. A hotel chain where one front desk serves every hotel is SSO. We reuse this picture through the page.

Three common misunderstandings, up front ​

  1. "OAuth is a login protocol." It is a delegation protocol. Login is OpenID Connect (or SAML). An access token does not tell the client who the user is.
  2. "PKCE is for mobile apps only." RFC 9700 makes it mandatory for public clients and recommended for confidential ones; OAuth 2.1 requires it for every client using the authorization code grant.
  3. "A SPA should store the access token in localStorage." Any XSS reads it. The current recommendation (RFC 10017) ranks a backend-for-frontend first: tokens stay on a server, the browser holds an HttpOnly cookie.

Where it comes from ​

  • 2007–2010, OAuth 1.0 / RFC 5849. Delegation for web APIs with per-request signatures; hard to implement correctly.
  • RFC 6749 and RFC 6750 (October 2012). OAuth 2.0 drops signatures in favour of TLS and bearer tokens, and defines four grants: authorization code, implicit, resource owner password credentials, client credentials. RFC 6749 already says "A maximum authorization code lifetime of 10 minutes is RECOMMENDED" and that a code used more than once must be denied.
  • RFC 7009 (2013) and RFC 7662 (2015): revocation and introspection. RFC 7591 (2015): dynamic client registration.
  • OpenID Connect Core 1.0 (2014; errata set 2 in December 2023). Identity layer: ID token, UserInfo, discovery, nonce, prompt, max_age, acr. Logout specs (RP-initiated, front-channel, back-channel) followed.
  • RFC 7636, PKCE (September 2015). Born for native apps whose redirect could be intercepted by another app.
  • RFC 8252 (2017): native apps "MUST NOT use embedded user-agents" (web views) and use the system browser. RFC 8414 (2018): authorization server metadata. RFC 8628 (2019): device grant.
  • RFC 8693 token exchange, RFC 8705 mTLS, RFC 8707 resource indicators (2020); RFC 9068 JWT access tokens, RFC 9101 JAR, RFC 9126 PAR (2021); RFC 9207 iss (2022); RFC 9449 DPoP (2023).
  • RFC 9700, OAuth 2.0 Security Best Current Practice (January 2025). The rules this chapter follows: "The resource owner password credentials grant [RFC6749] MUST NOT be used"; "clients SHOULD NOT use the implicit grant"; authorization servers "MUST utilize exact string matching" for redirect URIs.
  • RFC 10017, OAuth 2.0 for Browser-Based Applications (August 2026). Three architectures "presented in decreasing order of security": BFF, token-mediating backend, browser-based OAuth client.
  • OAuth 2.1 (draft-ietf-oauth-v2-1-17, last updated 2026-10-30, still an Internet-Draft). Consolidates the above: "features not specified in OAuth 2.0 core, such as PKCE, are required in OAuth 2.1", and implicit and password "are not specified in OAuth 2.1".
  • SAML 2.0 (OASIS, 2005). The XML predecessor for enterprise SSO; still everywhere in corporate federation. FAPI 2.0 Security Profile (OpenID Foundation) tightens OAuth for banking.

The concept catalogue ​

Roles: resource owner, client, authorization server, resource server Must-know ​

In plain words: The owner says yes, the authorization server writes the key, the client carries it, the resource server checks it.

Common misunderstanding: "The API and the login server must be one application." They are roles; one Laravel app with Passport can be both AS and RS, or Keycloak can be the AS for twenty APIs. What matters is that the RS trusts tokens from a specific issuer for a specific audience.

Definition: RFC 6749 section 1.1 defines the resource owner ("an entity capable of granting access to a protected resource"), the resource server (hosts the resources, accepts and responds using access tokens), the client (makes requests on behalf of the owner and with its authorization) and the authorization server (issues tokens after authenticating the owner and obtaining authorization). OpenID Connect renames the AS an OpenID Provider (OP) and the client a Relying Party (RP); SAML calls them Identity Provider (IdP) and Service Provider (SP).

 1  owner  -> client   "show my orders in the shop app"
 2  client -> AS       redirect: may I have orders:read for Ana?
 3  AS     -> owner    login + "Allow shop app to see your orders?"
 4  AS     -> client   code -> token (audience orders-api, scope orders:read)
 5  client -> RS       GET /orders  Authorization: Bearer <token>
 6  RS                 checks issuer, audience, expiry, scope -> 200

Real scenario: A shop runs Keycloak as AS/OP, a Go BFF as the client, and orders-api plus billing-api as resource servers; a partner's reporting tool is a second client that only gets orders:read. A Laravel app with Passport is all three for its own mobile app.

ProductAS / OPRS side
KeycloakRealm = issuer; clients, scopes, mappersAny API validating its JWTs or calling introspection
Laravel Passport/oauth/authorize, /oauth/token routesauth:api guard plus CheckToken middleware
Okta / Auth0Custom authorization servers / tenantsAPIs registered as audiences
GoOry Hydra or Dex as ASgo-oidc verifier or RFC 7662 client

Client types and client authentication Must-know ​

In plain words: A server can keep a secret; a browser bundle, a mobile app or a CLI cannot. The first is a confidential client, the rest are public clients.

Common misunderstanding: "Our mobile app has a client secret, so it is confidential." A secret compiled into an app is extracted in minutes with a decompiler; that client is public whether or not it sends a secret.

Definition: RFC 6749 section 2.1: confidential clients can keep credentials confidential, public clients cannot. Client authentication methods at the token endpoint (names from the OIDC and RFC 8414 registries): client_secret_basic (HTTP Basic), client_secret_post (form fields), private_key_jwt (a JWT assertion signed with the client's key), tls_client_auth and self_signed_tls_client_auth (RFC 8705 mTLS), and none for public clients. Public clients compensate with PKCE, exact redirect URIs and refresh token rotation.

Real scenario: A Go BFF uses private_key_jwt so no shared secret sits in config; a React SPA talks only to its BFF; an iOS app is a public client with a claimed https redirect; a nightly job uses client_secret_basic from a secrets manager.

ClientTypeAuth at token endpointNotes
Server-rendered web app, BFFConfidentialclient_secret_basic, private_key_jwt, mTLSBest place to hold tokens
SPA without backendPublicnone + PKCERFC 10017 pattern 3
Mobile / desktop appPublicnone + PKCESystem browser, RFC 8252
CLIPublicnone + PKCE (loopback) or device grantLoopback port may vary
MicroserviceConfidentialSecret, private_key_jwt or mTLSClient credentials

Authorization code grant Must-know ​

In plain words: The browser carries only a short, one-time code; the client swaps that code for tokens on a back channel the browser never sees.

Common misunderstanding: "The code is harmless, it is not a token." A stolen code plus the client's credentials (or no credentials, for a public client) is a token. That is why codes live 10 minutes at most, work once, and are bound to the client, the redirect_uri and (with PKCE) a secret only the real client knows.

Definition: RFC 6749 section 4.1. The authorization request is a browser redirect to the authorization endpoint with response_type=code, client_id, redirect_uri, scope, state (plus code_challenge and code_challenge_method for PKCE, nonce for OIDC). The response is a redirect to redirect_uri?code=...&state=... (and iss=... under RFC 9207). The token request is a POST with grant_type=authorization_code, code, redirect_uri, code_verifier and client authentication; the response is JSON with access_token, token_type, expires_in, optionally refresh_token, scope, and id_token for OIDC. Errors at the authorization endpoint come back on the redirect (error=access_denied, invalid_scope, login_required...); errors at the token endpoint are JSON with HTTP 400/401 (invalid_grant, invalid_client...).

BrowserBFF (confidential client)Authorization server / OPResource server (API)1 GET /login2 make state, nonce, code_verifier; store them3 302 + Set-Cookie flow=state (HttpOnly)4 GET /authorize?response_type=code&state&nonce&code_challenge&S2565 user authenticates (MFA), consents to scopes6 302 redirect_uri?code=...&state=...&iss=...7 GET /callback?code&state&iss (cookie)8 state == cookie, iss == issuer, flow taken once9 POST /token code + code_verifier + client auth10 SHA-256(verifier) == challenge? code unused?11 access_token, refresh_token, id_token12 verify id_token: sig (JWKS), iss, aud, exp, nonce13 302 / + Set-Cookie __Host-sid (no tokens)14 GET /api/orders (cookie only)15 GET /orders Authorization: Bearer at16 check sig, iss, aud, exp, scope
 1  GET https://id.example.com/authorize?response_type=code&client_id=shop-bff
        &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=openid%20profile%20orders%3Aread
        &state=Xb8...&nonce=n-0S6...&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
        &code_challenge_method=S256
 2  (user logs in, consents)
 3  HTTP/1.1 302 Found
    Location: https://app.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=Xb8...
              &iss=https%3A%2F%2Fid.example.com
 4  POST /token   Authorization: Basic c2hvcC1iZmY6...
    grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
    &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
 5  200 {"access_token":"...","token_type":"Bearer","expires_in":300,
        "refresh_token":"...","id_token":"eyJ...","scope":"openid profile orders:read"}

Real scenario: every "Sign in with Google" button; a Laravel app consuming a Passport server; Grafana logging in through Keycloak; a GitHub App acting for a user.

Fix / how to use it: use a library for the client side (golang.org/x/oauth2 + go-oidc, Socialite) and a product for the server side; see Go and Laravel.

PKCE: code_challenge, code_verifier, S256 Must-know ​

In plain words: Before the redirect the client invents a random secret, sends only its hash, and later proves it knows the original. A thief who catches the code does not have the original.

Common misunderstanding: "PKCE replaces state." PKCE stops code injection and stolen codes at the token endpoint. RFC 9700 says clients that ensured the AS supports PKCE "MAY rely on the CSRF protection provided by PKCE", that in OpenID Connect "the nonce parameter provides CSRF protection", and otherwise one-time state values bound to the user agent MUST be used. Defence in depth costs nothing here: keep all three.

Definition: RFC 7636. code_verifier is a high-entropy string of 43 to 128 characters from [A-Z] [a-z] [0-9] - . _ ~. code_challenge = BASE64URL(SHA256(ASCII(code_verifier))) with code_challenge_method=S256; the plain method sends the verifier itself and must not be used when S256 is possible. The AS stores the challenge with the code and, at /token, recomputes it from the code_verifier; a mismatch is invalid_grant. The RFC's own test vector: verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk gives challenge E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM (the Go tests check this).

     honest client                   attacker                        AS
 1   v = random(32 bytes) -> 43 chars
 2   /authorize ... code_challenge=S256(v)  ------------------------>  stores challenge with code C
 3   <-- redirect ?code=C (intercepted by a malicious app or a log) -->  attacker has C
 4                                    POST /token code=C (no v)  ---->  invalid_grant: no verifier
 5   POST /token code=C code_verifier=v --------------------------->  S256(v) == challenge -> tokens

Real scenario: a mobile app whose custom URL scheme is also claimed by a malicious app; an authorization code leaked in a proxy log; an attacker injecting their own code into a victim's session ("code injection") to link the victim to the attacker's account.

ProductPKCE support
KeycloakPer-client "PKCE method" setting (S256); identity-provider brokering can also use PKCE upstream
Laravel Passportphp artisan passport:client --public creates a PKCE client
Auth0, OktaAuthorization Code with PKCE is the documented flow for SPAs and native apps
golang.org/x/oauth2GenerateVerifier(), S256ChallengeOption(v), VerifierOption(v)

Fix / how to use it: pkce.go shows both sides; the Laravel controller in Laravel computes the challenge exactly as the Passport docs show.

Client credentials grant Must-know ​

In plain words: A service logs in as itself, with its own credentials, and gets a token. There is no user and no browser.

Common misunderstanding: "Client credentials tokens should come with a refresh token." RFC 6749 section 4.4.3 says a refresh token SHOULD NOT be included; the client just asks again. Another one: using a client credentials token and then trusting a user_id field the caller puts in the body is impersonation without control; use token exchange for "on behalf of".

Definition: POST /token with grant_type=client_credentials, optional scope (and resource from RFC 8707 to pick the API), client authentication. The token's subject is the client.

 1  billing-worker -> AS   POST /token grant_type=client_credentials&scope=inventory:read
                           &resource=https://inventory.example.com  (Basic auth)
 2  AS -> worker           {"access_token":"...","expires_in":600}   (no refresh_token)
 3  worker -> inventory    GET /stock  Authorization: Bearer ...
 4  t+590 s                TokenSource asks again (cached until near expiry)

Real scenario: a nightly export job calling the orders API; a payment webhook processor calling the ledger service; Laravel Passport's EnsureClientIsResourceOwner routes; Kubernetes workloads using projected service-account tokens as client assertions (federated workload identity).

Fix / how to use it: clientcredentials.Config in Go (machine/main.go), php artisan passport:client --client plus EnsureClientIsResourceOwner::using(...) in Laravel. Cache tokens; asking per request multiplies AS load (see rate limiting).

Device authorization grant (RFC 8628) Important ​

In plain words: The TV shows a short code and a URL; you type the code on your phone; the TV keeps asking "done yet?" until you approve.

Common misunderstanding: "Polling faster logs the user in faster." The device must wait interval seconds (5 if absent) and add 5 seconds on each slow_down; ignoring this gets the client rate-limited.

Definition: POST /device_authorization (Passport: /oauth/device/code) with client_id and scope returns device_code, user_code, verification_uri, optional verification_uri_complete, expires_in, interval. The device polls /token with grant_type=urn:ietf:params:oauth:grant-type:device_code and gets authorization_pending, slow_down, access_denied, expired_token or tokens.

 1  tv   -> AS    POST /device_authorization client_id=tv-app&scope=openid profile
 2  AS   -> tv    {"device_code":"GmRh...","user_code":"WDJB-MJHT","verification_uri":"https://id.example.com/device","interval":5,"expires_in":900}
 3  tv            shows "Go to id.example.com/device and enter WDJB-MJHT"
 4  tv   -> AS    POST /token grant_type=...:device_code&device_code=GmRh...   -> 400 authorization_pending
 5  phone -> AS   user logs in, enters WDJB-MJHT, approves
 6  tv   -> AS    POST /token ... -> 200 tokens

Real scenario: smart TV apps, the GitHub CLI and Azure CLI device login, IoT devices without keyboards, SSH sessions on headless servers. Phishing risk: an attacker can start a device flow and send the user a real verification URL with their code ("device code phishing"), so show the client name and ask for confirmation.

Refresh tokens and rotation Must-know ​

In plain words: The access token dies fast; the refresh token quietly fetches a new one without sending the user through login again.

Common misunderstanding: "A refresh token is just a longer access token." It is only ever sent to the AS, never to an API, and its theft is worse because it outlives the access token. That is why RFC 9700 says "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation".

Definition: POST /token with grant_type=refresh_token, refresh_token, optional narrower scope. With rotation, each use returns a new refresh token and invalidates the old; if an old one is presented again, the AS treats it as theft and revokes the whole token family. OIDC: request offline_access (and prompt=consent at some OPs) to get a refresh token that survives the IdP session.

 1  client  RT1 -> AS   refresh -> AT2, RT2   (RT1 now invalid)
 2  thief   RT1 -> AS   refresh -> 400 invalid_grant; AS revokes RT2 as well (reuse detection)
 3  client  RT2 -> AS   400 invalid_grant -> user must log in again (safe failure)

Real scenario: a BFF refreshing just before expiry (x/oauth2 refreshes 10 seconds early); two browser tabs refreshing at once with rotation and one of them losing (the classic "random logout" bug); Auth0 and Okta refresh token rotation; Keycloak's "Revoke Refresh Token" realm setting.

ProductRotation knob
KeycloakRealm settings → Tokens → "Revoke Refresh Token" (issue a new refresh token on every refresh)
Auth0Refresh Token Rotation: a new refresh token with each request (application setting)
OktaRefresh token rotation per app (product setting; not re-verified for this page)
Laravel PassportNew refresh token issued on each refresh; refreshTokensExpireIn()

Fix / how to use it: serialize refreshes per session (one in-flight refresh, others wait) and save the rotated token atomically; the Go freshToken saves the new pair; see Solving.

sql
-- Authorization-server side of rotation with reuse detection (PostgreSQL).
-- One statement: only one of two concurrent refreshes can win.
UPDATE refresh_tokens
SET    used_at = now()
WHERE  token_hash = encode(sha256($1::bytea), 'hex')
  AND  used_at IS NULL AND revoked_at IS NULL AND expires_at > now()
RETURNING family_id, user_id, client_id;
-- 0 rows and the hash exists with used_at set -> reuse: revoke the family
UPDATE refresh_tokens SET revoked_at = now() WHERE family_id = $2 AND revoked_at IS NULL;

The deprecated grants: implicit and password Important ​

In plain words: Implicit put the access token straight into the URL; password made the app collect the user's password. Both were shortcuts that leak.

Common misunderstanding: "The password grant is fine for our own first-party app." RFC 9700 says it MUST NOT be used: it "insecurely exposes the credentials of the resource owner to the client", does not work with MFA or passkeys, and trains users to type passwords outside the IdP. For first-party login, use the code flow against your own AS (it can skip the consent screen for first-party clients).

Definition: Implicit: response_type=token, token returned in the redirect fragment (#access_token=...), no client authentication, no refresh token, no way to bind the token to the client; RFC 9700: clients "SHOULD NOT use the implicit grant". Password: grant_type=password&username=...&password=.... OAuth 2.1 omits both. The Laravel Passport docs say "We no longer recommend using password grant tokens" and the same for implicit tokens.

 1  implicit: redirect https://spa.example.com/#access_token=eyJ...&token_type=Bearer
 2  browser history, extensions, and any script on the page now have the token
 3  password: app -> AS  grant_type=password&username=ana&password=hunter2  (app saw the password)

Real scenario: a 2015-era Angular SPA still on implicit; a mobile app with its own login form calling Passport's password grant; a migration plan: move SPAs to a BFF or code + PKCE, move first-party apps to the code flow with a first-party consent skip.

redirect_uri and exact matching Must-know ​

In plain words: The AS only sends codes back to addresses written down in advance, character for character.

Common misunderstanding: "Prefix or wildcard matching is fine for preview environments." https://app.example.com/callback* also matches https://app.example.com/callback/../../redirect?to=evil on a lax parser, and a wildcard subdomain matches a takeover of an abandoned CNAME. RFC 9700: authorization servers "MUST utilize exact string matching except for port numbers in localhost redirection URIs of native apps".

Definition: The client registers full redirect URIs. The authorization request's redirect_uri must equal one of them exactly (RFC 8252 allows any port on loopback http://127.0.0.1:{port}/ for native apps). The token request repeats the same redirect_uri (OAuth 2.1 makes this conditional). Clients and AS must also not contain open redirectors: endpoints that forward to a URL from a query parameter, because the AS's exact match is useless if the registered URI forwards elsewhere.

 1  registered:   https://app.example.com/callback
 2  request:      redirect_uri=https://app.example.com/callback?next=https://evil.example
 3  exact match:  rejected (query string differs)  -> invalid_request shown at the AS, no redirect
 4  lax prefix:   accepted -> code lands at /callback, which "helpfully" forwards to evil with the code in Referer

Real scenario: a marketing subdomain taken over through a dangling DNS record; a ?return_to= parameter on the callback that redirects anywhere (the Go code allows only local paths); per-pull-request preview URLs (register each one through dynamic registration or use one stable callback and a signed return_to).

state, nonce and the iss response parameter Must-know ​

In plain words: state ties the response to the browser that started the login; nonce ties the ID token to that login; iss tells the client which server answered.

Common misunderstanding: "state can be a constant or the return URL." A constant state gives no CSRF protection; an attacker sends the victim a callback URL with the attacker's code and the victim ends up logged into the attacker's account (login CSRF), then saves a card into it. state must be unguessable and bound to the user agent (cookie or session), and used once.

Definition: state (RFC 6749): opaque value the AS returns unchanged; RFC 9700: "Clients MUST prevent Cross-Site Request Forgery (CSRF)", using PKCE, the OIDC nonce, or a one-time state bound to the user agent. nonce (OIDC Core): "String value used to associate a Client session with an ID Token, and to mitigate replay attacks"; the client "MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent". iss (RFC 9207): the AS includes its issuer identifier in the authorization response; "The iss parameter serves as an effective countermeasure to "mix-up attacks"." The AS advertises authorization_response_iss_parameter_supported: true in its metadata, and then the client must require it.

     victim browser                         attacker                         client
 1                                          starts login at the client, gets code A for the attacker's account
 2                                          does not finish; sends victim https://app/callback?code=A&state=S_att
 3   victim clicks the link  ------------------------------------------------>  state check:
 4   without binding: client redeems A, victim is now logged in as the attacker
 5   with a cookie-bound state: cookie missing or different -> 400 "state mismatch"

Mix-up in one line: a client that talks to two authorization servers (say a real one and an attacker-run one registered through dynamic registration) sends a code from the honest AS to the attacker's token endpoint, because it believed the response came from the attacker's AS. Checking iss (or using a distinct redirect_uri per AS) prevents it.

Fix / how to use it: the Go Login stores state, nonce and the verifier server-side and sets a __Host-oidc-flow cookie with the state; Callback compares in constant time, takes the flow once, checks iss, then nonce after verifying the ID token.

Scopes vs claims vs permissions Must-know ​

In plain words: A scope is what the app asked to do; a claim is a fact in a token; a permission is what the user is really allowed to do, decided by your API.

Common misunderstanding: "If the token has orders:write, the user may write any order." The scope says the client may act in that area for this user. Whether Ana may edit order 991 is the API's authorization logic (ownership, roles, tenant); see Authorization Models.

Definition: scope is a space-delimited list of case-sensitive strings (RFC 6749 section 3.3); the AS may grant fewer than requested and then returns the granted scope. OIDC defines openid (required for OIDC), profile, email, address, phone, offline_access. Claims are name/value pairs in an ID token, UserInfo or JWT access token (sub, email, tid, roles...). RFC 8707 resource and the aud claim say which API a token is for. RFC 9396 authorization_details carries fine-grained structured requests ("pay 45 EUR to IBAN X") where a scope string is too coarse.

Real scenario: a third-party analytics app gets orders:read but the API still filters to the user's own tenant; an internal admin client gets orders:read orders:write and the API checks the admin role claim for refunds above a limit; Google asks for https://www.googleapis.com/auth/calendar.readonly and shows it on the consent screen.

ConceptLives inDecided byExample
ScopeRequest and token scopeAS + user consentorders:read
Audienceaud, resourceAShttps://api.example.com
ClaimID token, UserInfo, access tokenAS (from the user store)email_verified: true, tid
PermissionYour API's policyYour code"Ana may refund orders of tenant 7 up to 100 EUR"

Tokens: access, refresh, ID; bearer usage Must-know ​

In plain words: Whoever holds a bearer token can use it, like cash. Keep it short-lived, send it only over TLS, only in a header, only to the API it is for.

Common misunderstanding: "A JWT access token can be read by the client, so the client should read it." The access token is for the resource server; its format may change (opaque, encrypted) without notice. The client learns about the user from the ID token or UserInfo.

Definition: RFC 6750: send Authorization: Bearer <token> (form body allowed; query parameter discouraged, and RFC 9700 says clients MUST NOT pass access tokens in a URI query parameter). Errors: WWW-Authenticate: Bearer realm="...", error="invalid_token" with 401, error="insufficient_scope" with 403, error="invalid_request" with 400; a request without a token gets 401 with a bare challenge. RFC 6750 also says bearer tokens "SHOULD NOT be passed in page URLs". JWT access tokens follow RFC 9068: header typ: at+jwt, claims iss, exp, aud, sub, client_id, iat, jti, scope. Opaque tokens are random strings the RS checks by introspection.

 1  GET /orders HTTP/1.1
    Authorization: Bearer eyJ0eXAiOiJhdCtqd3QiLCJhbGciOiJSUzI1NiJ9...
 2  HTTP/1.1 403 Forbidden
    WWW-Authenticate: Bearer realm="orders", error="insufficient_scope", scope="orders:write"

Real scenario: a token copied from a log by a support engineer works for anyone until expiry (keep TTL short, scrub logs); an ID token sent to an API and accepted because the API only checked the signature (the typ and aud checks in resource.go stop that); an access token for billing-api replayed against orders-api (audience check).

Fix / how to use it: the JWT chapter covers signature algorithms and kid rotation; resource.go shows the RS checks.

Introspection and revocation: opaque vs JWT Important ​

In plain words: A JWT is checked locally with a public key, fast but unrevocable until it expires; an opaque token is checked by asking the AS, slower but instantly revocable.

Common misunderstanding: "Revoking a JWT access token at the AS stops it." The RS never asks the AS, so the token works until exp. Revocation (RFC 7009) is reliable for refresh tokens and for opaque access tokens that the RS introspects.

Definition: RFC 7662 introspection: the RS (authenticated as a client) posts token=...&token_type_hint=access_token to the introspection endpoint and gets JSON whose only required member is active, plus scope, client_id, sub, exp, aud, iss. RFC 7009 revocation: the client posts token and token_type_hint to the revocation endpoint; "The authorization server responds with HTTP status code 200 if the token has been revoked successfully or if the client submitted an invalid token" (so an attacker cannot probe tokens).

 1  RS -> AS   POST /introspect  token=2YotnFZFEjr1zCsicMWpAA  (Basic orders-api:...)
 2  AS -> RS   {"active":true,"scope":"orders:read","sub":"user-42","exp":1767225600,"aud":"https://api.example.com"}
 3  user clicks "sign out of all devices" -> AS revokes
 4  RS -> AS   (cache expired) -> {"active":false} -> 401 invalid_token
FormatCheckLatencyRevocation delayGood for
JWT (at+jwt)Local signature with cached JWKSMicrosecondsUp to expHigh-volume APIs, many services
Opaque + introspectionHTTP call to AS1 network round trip, cacheableCache TTLBanking, admin APIs, instant logout
JWT + short TTL + refreshLocalMicrosecondsMinutesThe usual compromise
Phantom token (gateway introspects, forwards JWT)Gateway introspects onceOne call at the edgeGateway cache TTLOpaque outside, JWT inside

ID token and OIDC claims Must-know ​

In plain words: The ID token is a signed note from the IdP to one app: "this is user sub, logged in at this time, in this way, for you."

Common misunderstanding: "Use email as the user key." Emails change and may be unverified at some providers; the stable key is the pair (iss, sub). Linking accounts by email alone lets anyone who registers an unverified address at a lax IdP take over the matching account.

Definition: OIDC Core section 2: a JWT with required claims iss, sub (unique and never reassigned within the issuer), aud (must contain the client id), exp, iat; conditionally auth_time (when max_age was requested), nonce (when sent), acr, amr (methods such as pwd, mfa, hwk), azp (authorized party, the client id the token was issued to), at_hash and c_hash (half-hashes binding the access token or code). Validation (section 3.1.3.7): signature with the OP's JWKS and an expected alg, iss exact match, aud contains the client id, azp if several audiences, exp in the future, nonce equal, auth_time within max_age if used.

 header  {"alg":"RS256","kid":"2026-11","typ":"JWT"}
 payload {"iss":"https://id.example.com/realms/shop","sub":"f3a1...","aud":"shop-bff",
          "exp":1767225900,"iat":1767225600,"auth_time":1767225590,"nonce":"n-0S6...",
          "acr":"urn:example:mfa","amr":["pwd","otp"],"sid":"idp-sess-1","email":"ana@example.com",
          "email_verified":true}

Real scenario: a support tool that keyed users by email merged two people after one changed address; a multi-IdP app that keyed by sub alone collided across issuers (always store iss too); a bank that requires acr for MFA before transfers and re-prompts with max_age=0.

UserInfo, discovery and dynamic client registration Important ​

In plain words: Discovery is the IdP's business card at a fixed URL; UserInfo is an API that returns profile claims; dynamic registration lets a client sign itself up by API.

Common misunderstanding: "Hard-code the JWKS URL and the endpoints." Endpoints and keys move; discovery plus a JWKS cache that refetches on unknown kid survives key rotation. And "UserInfo is the same as the ID token": UserInfo is a protected resource called with the access token; OIDC Core warns its response is not guaranteed to be about the sub in the ID token unless you check that "The sub (subject) Claim MUST always be returned in the UserInfo Response" and compare it.

Definition: OIDC Discovery: "OpenID Providers supporting Discovery MUST make a JSON document available at the path formed by concatenating the string /.well-known/openid-configuration to the Issuer". Key members: issuer (must equal the URL you fetched from), authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri, end_session_endpoint, registration_endpoint, scopes_supported, response_types_supported, code_challenge_methods_supported, token_endpoint_auth_methods_supported, id_token_signing_alg_values_supported, backchannel_logout_supported, authorization_response_iss_parameter_supported. Plain OAuth uses RFC 8414 at /.well-known/oauth-authorization-server. Dynamic client registration (RFC 7591, OIDC Registration): POST /register with metadata (redirect_uris, grant_types, token_endpoint_auth_method), response with client_id and possibly client_secret and a registration_access_token.

 1  RP -> OP   GET https://id.example.com/realms/shop/.well-known/openid-configuration
 2  OP -> RP   {"issuer":"https://id.example.com/realms/shop","jwks_uri":".../certs",...}
 3  RP         check issuer equals the configured value (else refuse: mix-up / misconfig)
 4  RP -> OP   GET jwks_uri -> keys by kid; cache; refetch when an unknown kid appears

Real scenario: Keycloak publishes discovery at /realms/{realm-name}/.well-known/openid-configuration; go-oidc's NewProvider fetches it and refuses an issuer mismatch; MCP and SaaS marketplaces use dynamic registration so each tenant installs a client without a ticket.

Authentication request options: prompt, max_age, acr, response_mode, hybrid flow Important ​

In plain words: Extra knobs on the login redirect: "do not show any UI", "make the user log in again", "I need MFA", "return the result as a form POST".

Common misunderstanding: "acr_values=mfa guarantees MFA." It is a request; the OP may not satisfy it. The RP must check the acr (or amr) claim in the ID token and refuse if it is weaker than required.

Definition: OIDC Core section 3.1.2.1: prompt is a space-delimited list of none (no UI; errors login_required, consent_required, interaction_required if the user would have to act), login (force re-authentication), consent, select_account; max_age is the "Maximum Authentication Age" in seconds, after which "the OP MUST attempt to actively re-authenticate" and include auth_time; acr_values requests authentication context classes; login_hint, id_token_hint, ui_locales, display are hints. response_mode chooses query, fragment or form_post (OAuth 2.0 Form Post Response Mode). The hybrid flow uses response_type=code id_token, code token or code id_token token: some tokens come in the front channel immediately, the code is redeemed later; the front-channel ID token carries c_hash to bind the code. It exists for apps that need the identity before the back-channel call; with a BFF the plain code flow is simpler and leaks less.

 1  step-up: user opens "transfer money"
 2  RP -> OP   /authorize?...&acr_values=urn:example:mfa&max_age=0&prompt=login
 3  OP         asks password + passkey
 4  RP         ID token: acr=urn:example:mfa, auth_time=now -> allow transfer
 5  silent check: /authorize?...&prompt=none -> error=login_required if the IdP session ended

Real scenario: a bank's step-up before payments (FAPI CIBA and acr); a dashboard that silently renews login with prompt=none in a hidden iframe (breaks when third-party cookies are blocked: prefer refresh tokens through a BFF); Google's prompt=select_account for users with several accounts.

Logout: RP-initiated, front-channel, back-channel Must-know ​

In plain words: There are three sessions to kill: your app's cookie, the IdP's session, and every other app that used the same IdP session.

Common misunderstanding: "Deleting our cookie logs the user out." The IdP session is still alive, so the next "Sign in" click logs the user straight back in without a password, which looks like a broken logout on a shared computer.

Definition: RP-initiated logout 1.0: the RP redirects the browser to the OP's end_session_endpoint with id_token_hint (RECOMMENDED), post_logout_redirect_uri (registered exactly), client_id, state, logout_hint. Front-channel logout 1.0: the OP renders <iframe src="frontchannel_logout_uri"> for each RP, adding iss and sid; the RP clears its cookie. The spec itself warns that user agents "are starting to block access to third-party content by default", which breaks this. Back-channel logout 1.0: the OP POSTs a logout_token (a JWT, RECOMMENDED typ: logout+jwt) to each RP's backchannel_logout_uri; required claims iss, aud, iat, exp, jti, events with member http://schemas.openid.net/event/backchannel-logout, and sub or sid; a nonce claim is PROHIBITED; the RP answers 200 with Cache-Control: no-store. OIDC Session Management adds a check_session_iframe for polling the OP's session, which suffers from the same third-party cookie blocking.

shop.example.comRP 1 session cookieadmin.example.comRP 2 session cookieOpenID Provider / IdP(Keycloak, Entra ID, Okta, Auth0)SSO session cookie at id.example.comone login, many RPsissues ID tokens per RP1 login (code+PKCE)2 code, id_token3 second app: no passwordCorporate IdPSAML 2.0 assertion (ADFS)Social IdPGoogle, GitHub (OIDC/OAuth)Partner tenant IdPOIDC, per-tenant issuerfederationbrokerRP-initiated logoutbrowser to end_session_endpointid_token_hint,post_logout_redirect_uriends the IdP sessionFront-channel logoutOP renders iframes to eachRP frontchannel_logout_urineeds third-party cookies(breaks in modern browsers)Back-channel logoutOP POSTs logout_token (JWT)to each RP backchannel URIRP deletes sessions by sid/subworks without the browser
 1  user clicks "Sign out" in shop
 2  shop BFF    deletes its session; 303 to OP end_session_endpoint?id_token_hint=...&post_logout_redirect_uri=https://app.example.com/
 3  OP          ends the SSO session sid=idp-sess-1
 4  OP -> admin POST /backchannel-logout  logout_token=eyJ...(sid=idp-sess-1)
 5  admin       deletes all sessions with idp_sid=idp-sess-1 -> 200
 6  OP -> browser 302 https://app.example.com/

Real scenario: a hospital workstation shared by nurses (back-channel logout must reach every RP); an employee offboarded in Entra ID whose sessions in internal apps should end now (back-channel logout or short sessions plus continuous access evaluation); Keycloak supports all three logout styles per client.

MechanismNeeds browserThird-party cookiesReliability
RP-initiatedYes (redirect)NoEnds the OP session; other RPs untouched
Front-channelYes (iframes)YesBreaks in Safari, Firefox and Chrome with cookie partitioning
Back-channelNoNoBest; RP must map sid/sub to its sessions
Short sessions + refreshNoNoLogout effective within access token TTL

Single sign-on, SAML 2.0 and federation Must-know ​

In plain words: SSO means the IdP remembers you with its own cookie; when the second app sends you there, it answers immediately with a new code for that app.

Common misunderstanding: "SSO means apps share one session cookie." They do not; each app has its own session. What is shared is the IdP session (a cookie on the IdP's domain). Sharing a cookie across *.example.com is not SSO; it is a shared session with all the subdomain risks of cookie scoping.

Definition: SP-initiated SSO starts at the app (the usual OIDC flow, or SAML AuthnRequest). IdP-initiated SSO starts at an IdP portal tile that posts a SAML response to the SP unsolicited; it has no request to bind to, so it is open to login CSRF and assertion injection; OIDC has no direct equivalent (OIDC "third-party initiated login" sends the user to the RP's initiate_login_uri, which then starts a normal SP-initiated flow). SAML 2.0 (OASIS): XML assertions signed with XML Signature, carried by bindings (HTTP Redirect, HTTP POST, HTTP Artifact, SOAP) in profiles such as the Web Browser SSO Profile and Single Logout Profile. Federation: an app trusts an IdP run by another organisation (a partner's Entra ID, a university's Shibboleth). Identity brokering: your IdP (Keycloak, Auth0, Cognito) sits in the middle, accepts logins from upstream IdPs (SAML, OIDC, social), maps attributes, and issues its own tokens to your apps; your apps integrate once. Social login: a brokered or direct login with Google, GitHub, Apple, Facebook; Laravel Socialite "currently supports authentication via Facebook, X, LinkedIn, Google, GitHub, GitLab, Bitbucket, and Slack".

 1  browser -> shop      not logged in -> 302 to OP /authorize (client shop)
 2  browser -> OP        no OP cookie -> login + MFA -> OP sets its session cookie
 3  OP -> shop           code -> shop session
 4  browser -> admin     not logged in -> 302 to OP /authorize (client admin)
 5  browser -> OP        OP cookie present, policy ok -> no prompt
 6  OP -> admin          code at once -> admin session   (that is SSO)
AspectSAML 2.0OpenID Connect
FormatXML assertion, XML SignatureJSON, JWT (JWS)
TransportBrowser POST of a base64 form, Redirect, ArtifactRedirect with code, back-channel token call
Who uses itEnterprise SSO, legacy SaaS, government, universitiesModern web, mobile, APIs
API accessNot designed for it (SAML bearer grant RFC 7522 bridges)Same AS issues access tokens
LogoutSingle Logout Profile (fragile)RP-initiated, back-channel
Classic bugsXML signature wrapping, accepting unsigned assertionsMissing aud/nonce checks, alg confusion
DiscoveryMetadata XML.well-known/openid-configuration

Real scenario: a B2B SaaS that must accept each customer's SAML IdP (Okta, ADFS, Entra ID) puts Keycloak or Auth0 in front as a broker and speaks only OIDC to its own services; Dex in Kubernetes "acts as a portal to other identity providers through “connectors”" (LDAP, SAML, GitHub) for kubectl login.

BFF and token storage for browser apps Must-know ​

In plain words: The safest place for tokens in a browser app is not the browser. A small server (backend-for-frontend) does the OAuth dance, keeps the tokens, and gives the browser an HttpOnly cookie.

Common misunderstanding: "HttpOnly cookies are worse than tokens because of CSRF." CSRF is solved with SameSite=Lax or Strict, __Host- cookies and a CSRF token or Sec-Fetch-Site check (web sessions). XSS stealing a refresh token from localStorage is not solvable after the fact.

Definition: RFC 10017 ranks three architectures "in decreasing order of security": (1) BFF: a confidential client on the server; the browser talks only to the BFF with a cookie, and the BFF proxies API calls adding the access token; (2) token-mediating backend: the backend does the code exchange and keeps the refresh token, but hands access tokens to the JavaScript; (3) browser-based OAuth client: the SPA itself does code + PKCE and holds tokens (in memory, ideally in a Web Worker), with refresh token rotation or DPoP. XSS in pattern 1 can still make calls through the BFF while the page is open, but cannot exfiltrate tokens for later.

BFF (recommended)Tokens stay on the serverBrowser: __Host-sid HttpOnlyBFF proxies /api with BearerXSS can call /api while openXSS cannot steal tokensToken-mediating backendBackend does code exchangekeeps refresh tokenJS gets access tokenXSS steals access tokens(short-lived)Browser-only clientJS does code + PKCEtokens in memory or storagelocalStorage: readable by XSSrefresh token must rotateor be DPoP-boundmore JavaScript holds credentials, larger blast radius of XSSRFC 10017 (OAuth 2.0 for Browser-Based Applications) orders the patterns this way
StorageReadable by XSSSurvives reloadSent automaticallyVerdict
BFF server + HttpOnly cookieNoYesYes (needs CSRF defence)Recommended
JS memory / Web WorkerHard (worker isolates)No (refresh needed)NoAcceptable for pattern 3
sessionStorageYesPer tabNoAvoid for refresh tokens
localStorageYesYesNoAvoid
Non-HttpOnly cookieYesYesYesWorst of both

Real scenario: Duende BFF (.NET), the Go rp package here, and Laravel with Sanctum SPA mode are BFFs; an Angular app moving from implicit to a BFF removes every token from the browser; a mobile app is not a browser app: it uses code + PKCE with tokens in the OS keychain.

Hardening the flow: PAR, JAR, mTLS, DPoP, FAPI Important ​

In plain words: Move the request off the URL (PAR), sign it (JAR), and make stolen tokens useless without a private key (mTLS or DPoP).

Common misunderstanding: "TLS makes bearer tokens safe." TLS protects the wire; it does not help when the token leaks from a log, a browser extension, a compromised proxy or a misconfigured RS that forwards it. Sender-constraining binds the token to a key the thief does not have.

Definition:

  • PAR (RFC 9126): the client POSTs the whole authorization request to the pushed_authorization_request_endpoint (with client authentication) and gets request_uri (form urn:ietf:params:oauth:request_uri:...) and expires_in; the browser redirect then carries only client_id and request_uri. Parameters cannot be tampered with or leaked in the front channel, and the AS authenticates the client before any user interaction.
  • JAR (RFC 9101): the authorization request as a signed (optionally encrypted) JWT in request or by reference in request_uri.
  • mTLS (RFC 8705): client authentication with a TLS client certificate (tls_client_auth with a PKI-issued certificate, self_signed_tls_client_auth), and certificate-bound access tokens: the token carries cnf: {"x5t#S256": "<cert thumbprint>"} and the RS compares it with the client certificate of the connection. See mTLS.
  • DPoP (RFC 9449): the client signs a small JWT (typ: dpop+jwt, jwk header, claims jti, htm, htu, iat, and ath = hash of the access token at the RS) for every request in a DPoP header; tokens have token_type: DPoP and cnf: {"jkt": "<key thumbprint>"}; the RS sends Authorization: DPoP <token>; servers may demand a server nonce with error="use_dpop_nonce"; bad proofs give invalid_dpop_proof. Works for SPAs and mobile apps where mTLS is impractical.
  • FAPI 2.0 Security Profile (OpenID Foundation): for open banking and high-value APIs; the authorization server "shall reject authorization requests sent without [RFC9126]" (PAR), shall require PKCE, "shall only support confidential clients", "shall only issue sender-constrained access tokens" (mTLS or DPoP), and rejects the password grant.
 1  client -> AS   POST /par  (private_key_jwt) response_type=code&client_id=bank-app&...&code_challenge=...
 2  AS -> client   201 {"request_uri":"urn:ietf:params:oauth:request_uri:6esc_11ACC5bwc","expires_in":60}
 3  browser -> AS  GET /authorize?client_id=bank-app&request_uri=urn:ietf:params:oauth:request_uri:6esc_11ACC5bwc
 4  client -> AS   POST /token ... DPoP: eyJ0eXAiOiJkcG9wK2p3dCIs...  -> token_type=DPoP, cnf.jkt
 5  client -> RS   GET /accounts  Authorization: DPoP <at>  DPoP: <proof with ath, htm=GET, htu>
 6  thief -> RS    GET /accounts  Authorization: DPoP <at>  (no private key -> no valid proof) -> 401
MechanismProtectsBest forProducts
PARRequest integrity and confidentialityAny confidential client, FAPIKeycloak, Okta, Auth0, Ory Hydra
JARRequest integrity (signed)Regulated ecosystemsKeycloak, FAPI servers
mTLS client auth + bound tokensClient identity, token replayServer-to-server, bankingKeycloak, Ping, Envoy/Istio at the RS
DPoPToken replaySPAs, mobile, public clientsKeycloak, Okta, Auth0
FAPI 2.0All of the above as a profileOpen banking (UK, Brazil, Australia)Certified OPs

Token exchange and delegation (RFC 8693) Important ​

In plain words: An API that received a user's token trades it at the AS for a new, narrower token to call the next API, instead of forwarding the original.

Common misunderstanding: "Just forward the user's token to every downstream service." Then every service's audience must be in the token, any compromised service can replay it everywhere, and downstream logs cannot tell which service acted.

Definition: POST /token with grant_type=urn:ietf:params:oauth:grant-type:token-exchange, subject_token and subject_token_type (for example urn:ietf:params:oauth:token-type:access_token), optional actor_token/actor_token_type, audience or resource, scope, requested_token_type. The response adds issued_token_type. RFC 8693 separates impersonation (the new token is just "user B"; A becomes indistinguishable from B) from delegation ("principal A still has its own identity separate from B"), expressed with the act (actor) claim; may_act says who is allowed to act for the subject. Errors include invalid_request and invalid_target.

 1  BFF -> orders-api           Bearer AT1 (aud=orders-api, sub=user-42, scope=orders:read orders:create)
 2  orders-api -> AS            token-exchange subject_token=AT1 actor_token=<orders-api cred> audience=billing-api scope=invoices:read
 3  AS -> orders-api            AT2 (aud=billing-api, sub=user-42, act={"sub":"orders-api"}, exp=+60 s)
 4  orders-api -> billing-api   Bearer AT2   -> billing logs "user-42 via orders-api"

Real scenario: a support agent "viewing as" a customer (impersonation with an act claim for audit); Kubernetes and cloud workload identity federation (a CI job's OIDC token exchanged for cloud credentials, as AWS STS AssumeRoleWithWebIdentity does in spirit); a gateway exchanging an external token for an internal one. Keycloak supports standard token exchange; Okta, Auth0 (custom token exchange) and Entra ID's on-behalf-of flow solve the same problem with product-specific variants.

Multi-tenant identity Important ​

In plain words: In a SaaS each customer may bring their own IdP or live in their own realm; the token must say which tenant it belongs to, and your API must check it.

Common misunderstanding: "Google's hd parameter restricts logins to our domain." It only optimizes the account chooser; Google's docs say to verify that the ID token "has a hd claim that matches an accepted domain". Same with Entra ID's multi-tenant common endpoint: you must check the tenant (tid) claim yourself, or any Microsoft tenant can log in.

Definition: Patterns: one issuer per tenant (Keycloak realm per tenant https://id.example.com/realms/{tenant}, Entra ID per-tenant issuers, Cognito user pool per tenant with issuer https://cognito-idp.{region}.amazonaws.com/{userPoolId}), or one issuer with a tenant claim (Auth0 Organizations org_id, Okta orgs, a custom tenant_id claim). The RP stores (iss, sub) and maps issuer to tenant; the RS validates iss against the tenant of the URL or resource. Home realm discovery picks the IdP from the email domain or the subdomain.

PatternIsolationCostExample
Issuer per tenantStrong: keys, policies, users separateMany realms to operateKeycloak realms, Cognito pools
One issuer + tenant claimLogicalCheap; one configAuth0 Organizations, custom claim
Broker per customer IdPCustomer controls usersMapping and supportKeycloak/Auth0 + customer SAML/OIDC
Multi-tenant cloud IdP endpointAny tenant can tryMust allow-list tid/hdEntra ID common, Google Workspace hd

Fix / how to use it: allow-list issuers per tenant, never "any issuer that validates"; see database multi-tenancy for data isolation.

Products Good to know ​

In plain words: Do not write an authorization server unless that is your product. Pick one of these and spend your time on validation and policy.

Common misunderstanding: "Our framework's OAuth package is an IdP." Laravel Passport is an OAuth 2.0 authorization server (on the League OAuth2 Server) for your Laravel app; it is not an OpenID Provider with SSO sessions, federation and logout. Socialite is a client.

Definition: a map of the products a practitioner meets.

ProductKindNotable
KeycloakOpen-source IdP (Red Hat)Realms, SSO and single sign-out, OIDC, OAuth 2.0, SAML, identity brokering, social login, user federation (LDAP), PAR, DPoP, token exchange
Auth0 (Okta)SaaS IdPUniversal Login, Actions, Organizations, refresh token rotation
Okta Workforce / Customer IdentitySaaS IdPCustom authorization servers; Authorization Code with PKCE for SPA and native
Microsoft Entra IDCloud IdPPer-tenant issuers, tid, on-behalf-of flow, Conditional Access
Amazon CognitoCloud user poolsPer-pool issuer, hosted UI, federation with SAML/OIDC/social
Ory HydraOAuth 2.0 / OIDC server"Headless": you bring login and consent UI (Ory Kratos or your own)
DexFederated OIDC providerConnectors to LDAP, SAML, GitHub, Google; common for Kubernetes
Laravel PassportOAuth 2.0 server inside LaravelPKCE, device, client credentials, scopes; default token lifetime one year
Laravel SocialiteOAuth clientGitHub, Google, Facebook, X, LinkedIn, GitLab, Bitbucket, Slack; community providers
golang.org/x/oauth2Go clientPKCE helpers, TokenSource refresh, device grant, clientcredentials
github.com/coreos/go-oidc/v3Go OIDC verifierDiscovery, JWKS cache, IDTokenVerifier

Mechanics ​

Endpoints and parameters ​

EndpointMethodParametersResponse
AuthorizationGET (browser)response_type, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, nonce, prompt, max_age, acr_values, login_hint, response_mode, request_uriRedirect with code, state, iss or error
TokenPOST formgrant_type, code, redirect_uri, code_verifier, refresh_token, scope, resource, device_code, subject_token, client authJSON: access_token, token_type, expires_in, refresh_token, id_token, scope
PARPOST formAll authorization parameters + client auth201 request_uri, expires_in
Device authorizationPOST formclient_id, scopedevice_code, user_code, verification_uri, interval, expires_in
IntrospectionPOST formtoken, token_type_hint + RS authactive, scope, sub, exp, aud
RevocationPOST formtoken, token_type_hint + client auth200 (also for unknown tokens)
UserInfoGET/POSTAuthorization: BearerJSON claims with sub
JWKSGETnone{"keys":[...]}
End sessionGET (browser)id_token_hint, post_logout_redirect_uri, client_id, stateRedirect
RegistrationPOST JSONClient metadataclient_id, client_secret, registration_access_token

Error codes ​

WhereerrorMeaningClient action
Token endpoint (400)invalid_grantCode or refresh token invalid, expired, revoked, reused, wrong redirect_uri, other client, PKCE mismatchRestart login; for refresh, drop the session
Token endpoint (401)invalid_clientClient authentication failed: unknown client, wrong secret, wrong methodFix configuration, rotate secret; do not retry blindly
Token endpointinvalid_requestMissing or repeated parameter, two auth methodsBug in the client
Token endpointunauthorized_clientClient not allowed this grantEnable grant on the client
Token endpointunsupported_grant_typeAS does not support the grantUse another grant
Token / authorizationinvalid_scopeUnknown or excessive scopeAsk for less
Authorization redirectaccess_deniedUser or policy said noShow a message, no retry loop
Authorization (OIDC)login_required, consent_required, interaction_required, account_selection_requiredprompt=none could not complete silentlyRedirect with UI
Device pollingauthorization_pending, slow_down, expired_tokenWaiting, too fast, too lateWait interval, add 5 s, restart
Resource server (401)invalid_tokenExpired, bad signature, wrong aud/iss, revokedRefresh once, then log in
Resource server (403)insufficient_scopeToken lacks a scopeAsk for consent to more scope
Resource server (400)invalid_requestMalformed request, token in two placesBug
DPoPinvalid_dpop_proof, use_dpop_nonceBad proof, nonce requiredRe-sign with the server nonce
Token exchangeinvalid_targetAudience/resource not allowedAsk for an allowed audience
SocialiteInvalidStateExceptionstate in session does not matchSession lost (domain, SameSite) or CSRF

Knobs and numbers ​

KnobTypical valueSource / product
Authorization code lifetime30 s to 10 min, one useRFC 6749: 10 minutes maximum RECOMMENDED
Access token TTL5 to 15 min for APIsProduct setting; Passport default is one year (shorten it)
Refresh token TTL8 h idle to 30–90 days absoluteKeycloak "SSO Session Idle/Max", Auth0 rotation lifetime
code_verifier length43–128 chars; 43 from 32 random bytesRFC 7636
Device interval5 s default, +5 s per slow_downRFC 8628
Device user_code8 characters, unambiguous alphabetPassport char(8); RFC 8628 guidance
PAR expires_in60 s typical (short)RFC 9126 examples
JWKS cacheMinutes to hours, refetch on unknown kidgo-oidc RemoteKeySet
Clock skew allowance30–120 sLibrary setting; keep NTP
x/oauth2 early refresh10 s before expirydefaultExpiryDelta in golang.org/x/oauth2
Introspection cache10–60 s (= accepted revocation delay)Gateway / RS setting

What a login costs ​

StepRound tripsEstimate (same region)
Discovery + JWKS2, cachedOnce per process
Redirect to AS and back2 browser navigations100–300 ms plus user time
Token request1 server-to-server20–100 ms
ID token verification0 (local)Microseconds per RSA-2048 verify
Per API call with JWT0 to the ASSignature check only
Per API call with introspection1 (or cache hit)5–30 ms uncached (estimate; see latency budgets)

Go ​

Before: the login everyone writes first ​

Bad design, not broken code: constant state, no PKCE, no nonce, the ID token decoded but not verified, the user keyed by email, the access token put in a redirect URL, the callback URL (with the code) logged, and an open redirect.

go
// Command before is the login people write first. It works in a demo and
// fails a security review: no state, no PKCE, no nonce, an unverified ID
// token, tokens in URLs and logs, and an open redirect. Bad design, not
// broken code: it compiles and runs.
package main

import (
	"encoding/base64"
	"encoding/json"
	"log"
	"net/http"
	"net/url"
	"strings"

	"golang.org/x/oauth2"
)

var conf = oauth2.Config{
	ClientID:     "shop-spa",
	ClientSecret: "hard-coded-secret", // shipped to every browser bundle in the SPA version
	RedirectURL:  "https://app.example.com/callback",
	Scopes:       []string{"openid", "email"},
	Endpoint: oauth2.Endpoint{
		AuthURL:  "https://id.example.com/authorize",
		TokenURL: "https://id.example.com/token",
	},
}

func main() {
	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		// Constant state: a login CSRF can bind the victim to the attacker's account.
		http.Redirect(w, r, conf.AuthCodeURL("state"), http.StatusFound)
	})
	http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		log.Printf("callback %s", r.URL.String()) // the code lands in logs
		// No state check, no PKCE verifier: an injected code is accepted.
		tok, err := conf.Exchange(r.Context(), r.URL.Query().Get("code"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadGateway)
			return
		}
		raw, _ := tok.Extra("id_token").(string)
		// Decoding is not verifying: no signature, iss, aud, exp or nonce check.
		parts := strings.Split(raw, ".")
		if len(parts) == 3 {
			payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
			var c map[string]any
			_ = json.Unmarshal(payload, &c)
			log.Printf("logged in %v", c["email"]) // email is not a stable identifier
		}
		// Access token in the URL: browser history, Referer, proxy logs.
		next := r.URL.Query().Get("next") // open redirector
		http.Redirect(w, r, next+"?access_token="+url.QueryEscape(tok.AccessToken), http.StatusFound)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

After: PKCE for both sides ​

The verifier and S256 challenge for the client, and Verify for an authorization server, with the RFC 7636 test vector:

go
// Package pkce implements RFC 7636 Proof Key for Code Exchange for both
// sides: the client creates a verifier and an S256 challenge; the
// authorization server checks the verifier against the stored challenge.
package pkce

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"errors"
)

// MethodS256 is the only method this package accepts. RFC 7636 also defines
// "plain", which RFC 9700 says servers should not allow.
const MethodS256 = "S256"

var (
	// ErrVerifierFormat means the verifier breaks RFC 7636 section 4.1:
	// 43 to 128 characters from [A-Z] [a-z] [0-9] "-" "." "_" "~".
	ErrVerifierFormat = errors.New("pkce: code_verifier must be 43-128 unreserved characters")
	// ErrMethod means the client asked for a method other than S256.
	ErrMethod = errors.New("pkce: code_challenge_method must be S256")
	// ErrMismatch is what the token endpoint turns into invalid_grant.
	ErrMismatch = errors.New("pkce: code_verifier does not match code_challenge")
)

// NewVerifier returns 32 random bytes as base64url without padding:
// exactly 43 characters, 256 bits of entropy.
func NewVerifier() (string, error) {
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Challenge computes BASE64URL(SHA256(ASCII(verifier))).
func Challenge(verifier string) string {
	sum := sha256.Sum256([]byte(verifier))
	return base64.RawURLEncoding.EncodeToString(sum[:])
}

// ValidVerifier checks length and alphabet.
func ValidVerifier(v string) bool {
	if len(v) < 43 || len(v) > 128 {
		return false
	}
	for i := 0; i < len(v); i++ {
		c := v[i]
		switch {
		case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
		case c == '-', c == '.', c == '_', c == '~':
		default:
			return false
		}
	}
	return true
}

// Verify is the authorization server side, run while redeeming the code.
// challenge and method are what the server stored with the code.
func Verify(verifier, challenge, method string) error {
	if method != MethodS256 {
		return ErrMethod
	}
	if !ValidVerifier(verifier) {
		return ErrVerifierFormat
	}
	got := Challenge(verifier)
	if subtle.ConstantTimeCompare([]byte(got), []byte(challenge)) != 1 {
		return ErrMismatch
	}
	return nil
}
go
package pkce

import (
	"errors"
	"strings"
	"testing"

	"golang.org/x/oauth2"
)

// The example from RFC 7636 Appendix B.
const (
	rfcVerifier  = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
	rfcChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
)

func TestChallengeMatchesRFC7636AppendixB(t *testing.T) {
	if got := Challenge(rfcVerifier); got != rfcChallenge {
		t.Fatalf("Challenge = %s, want %s", got, rfcChallenge)
	}
}

func TestChallengeMatchesXOAuth2(t *testing.T) {
	v := oauth2.GenerateVerifier()
	if Challenge(v) != oauth2.S256ChallengeFromVerifier(v) {
		t.Fatal("our S256 differs from golang.org/x/oauth2")
	}
}

func TestNewVerifierIsValidAndUnique(t *testing.T) {
	a, err := NewVerifier()
	if err != nil {
		t.Fatal(err)
	}
	b, _ := NewVerifier()
	if len(a) != 43 || !ValidVerifier(a) {
		t.Fatalf("verifier %q is not 43 valid characters", a)
	}
	if a == b {
		t.Fatal("two verifiers are equal")
	}
}

func TestVerify(t *testing.T) {
	cases := []struct {
		name      string
		verifier  string
		challenge string
		method    string
		want      error
	}{
		{"rfc vector", rfcVerifier, rfcChallenge, "S256", nil},
		{"wrong verifier", strings.Repeat("a", 43), rfcChallenge, "S256", ErrMismatch},
		{"plain refused", rfcVerifier, rfcVerifier, "plain", ErrMethod},
		{"too short", "abc", rfcChallenge, "S256", ErrVerifierFormat},
		{"bad alphabet", strings.Repeat("a", 42) + "+", rfcChallenge, "S256", ErrVerifierFormat},
		{"too long", strings.Repeat("a", 129), rfcChallenge, "S256", ErrVerifierFormat},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if err := Verify(c.verifier, c.challenge, c.method); !errors.Is(err, c.want) {
				t.Fatalf("Verify = %v, want %v", err, c.want)
			}
		})
	}
}

After: an OIDC relying party as a BFF ​

The store of pending flows and sessions (memory for tests; Redis or SQL in production):

go
package rp

import (
	"context"
	"errors"
	"sync"
	"time"

	"golang.org/x/oauth2"
)

// ErrNotFound is returned for unknown or expired records.
var ErrNotFound = errors.New("rp: not found")

// Session is the BFF's server-side record. The browser only ever holds the
// opaque session id in an HttpOnly cookie; tokens never reach JavaScript.
type Session struct {
	ID        string
	Subject   string // ID token "sub"
	IdPSID    string // ID token "sid", used by back-channel logout
	IDToken   string // raw, kept for id_token_hint at logout
	Token     *oauth2.Token
	CreatedAt time.Time
}

// Flow is one pending login: created at /login, consumed once at /callback.
type Flow struct {
	State     string
	Nonce     string
	Verifier  string
	ReturnTo  string
	ExpiresAt time.Time
}

// Store persists flows and sessions. Production uses Redis or SQL (see the
// sql/ snippet); MemoryStore is for one process and tests.
type Store interface {
	PutFlow(ctx context.Context, f Flow) error
	// TakeFlow returns and deletes the flow, so a state value works once.
	TakeFlow(ctx context.Context, state string) (Flow, error)
	PutSession(ctx context.Context, s *Session) error
	GetSession(ctx context.Context, id string) (*Session, error)
	DeleteSession(ctx context.Context, id string) error
	// DeleteByIdP removes sessions for a back-channel logout (sid or sub).
	DeleteByIdP(ctx context.Context, subject, sid string) (int, error)
}

// MemoryStore is a mutex-guarded map implementation of Store.
type MemoryStore struct {
	mu       sync.Mutex
	flows    map[string]Flow
	sessions map[string]*Session
	now      func() time.Time
}

// NewMemoryStore returns an empty store.
func NewMemoryStore() *MemoryStore {
	return &MemoryStore{flows: map[string]Flow{}, sessions: map[string]*Session{}, now: time.Now}
}

func (m *MemoryStore) PutFlow(_ context.Context, f Flow) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.flows[f.State] = f
	return nil
}

func (m *MemoryStore) TakeFlow(_ context.Context, state string) (Flow, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	f, ok := m.flows[state]
	delete(m.flows, state)
	if !ok || m.now().After(f.ExpiresAt) {
		return Flow{}, ErrNotFound
	}
	return f, nil
}

func (m *MemoryStore) PutSession(_ context.Context, s *Session) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	cp := *s
	m.sessions[s.ID] = &cp
	return nil
}

func (m *MemoryStore) GetSession(_ context.Context, id string) (*Session, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	s, ok := m.sessions[id]
	if !ok {
		return nil, ErrNotFound
	}
	cp := *s
	return &cp, nil
}

func (m *MemoryStore) DeleteSession(_ context.Context, id string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	delete(m.sessions, id)
	return nil
}

func (m *MemoryStore) DeleteByIdP(_ context.Context, subject, sid string) (int, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	n := 0
	for id, s := range m.sessions {
		if (sid != "" && s.IdPSID == sid) || (sid == "" && s.Subject == subject) {
			delete(m.sessions, id)
			n++
		}
	}
	return n, nil
}

Discovery, login with PKCE/state/nonce, the callback checks (cookie-bound state, single use, RFC 9207 iss, code exchange with the verifier, ID token verification, nonce, at_hash), the HttpOnly session, the API proxy with refresh and rotation, RP-initiated logout and back-channel logout:

go
// Package rp is an OpenID Connect relying party in the backend-for-frontend
// (BFF) shape: authorization code + PKCE, state and nonce, discovery,
// ID token verification with go-oidc, refresh, an HttpOnly session cookie,
// RP-initiated logout and back-channel logout.
package rp

import (
	"context"
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"time"

	"github.com/coreos/go-oidc/v3/oidc"
	"golang.org/x/oauth2"
)

const (
	flowCookie    = "__Host-oidc-flow"
	sessionCookie = "__Host-sid"
	flowTTL       = 10 * time.Minute
	backchannel   = "http://schemas.openid.net/event/backchannel-logout"
)

// Config is what the operator sets; everything else comes from discovery.
type Config struct {
	Issuer       string // exact issuer, e.g. https://id.example.com/realms/shop
	ClientID     string
	ClientSecret string // confidential client: the BFF runs on a server
	RedirectURL  string // registered exactly, e.g. https://app.example.com/callback
	PostLogout   string // registered post_logout_redirect_uri
	Scopes       []string
	APIUpstream  *url.URL // resource server the BFF proxies to
	Store        Store
	Logger       *slog.Logger
}

// RP holds the discovered provider and the handlers.
type RP struct {
	cfg        Config
	provider   *oidc.Provider
	oauth      oauth2.Config
	idVerifier *oidc.IDTokenVerifier
	meta       providerMeta
	now        func() time.Time
}

type providerMeta struct {
	EndSession     string   `json:"end_session_endpoint"`
	IssParameter   bool     `json:"authorization_response_iss_parameter_supported"`
	CodeChallenges []string `json:"code_challenge_methods_supported"`
}

// New fetches {issuer}/.well-known/openid-configuration once. Pass a context
// made with oidc.ClientContext to use a custom HTTP client.
func New(ctx context.Context, cfg Config) (*RP, error) {
	p, err := oidc.NewProvider(ctx, cfg.Issuer)
	if err != nil {
		return nil, fmt.Errorf("discovery: %w", err)
	}
	var meta providerMeta
	if err := p.Claims(&meta); err != nil {
		return nil, fmt.Errorf("discovery metadata: %w", err)
	}
	if !contains(meta.CodeChallenges, "S256") {
		return nil, errors.New("provider does not advertise PKCE S256")
	}
	scopes := append([]string{oidc.ScopeOpenID}, cfg.Scopes...)
	if cfg.Logger == nil {
		cfg.Logger = slog.Default()
	}
	return &RP{
		cfg:      cfg,
		provider: p,
		oauth: oauth2.Config{
			ClientID:     cfg.ClientID,
			ClientSecret: cfg.ClientSecret,
			Endpoint:     p.Endpoint(),
			RedirectURL:  cfg.RedirectURL,
			Scopes:       scopes,
		},
		// Checks signature (JWKS from discovery), iss, aud == ClientID, exp.
		idVerifier: p.Verifier(&oidc.Config{ClientID: cfg.ClientID}),
		meta:       meta,
		now:        time.Now,
	}, nil
}

// Routes mounts the BFF endpoints.
func (r *RP) Routes() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /login", r.Login)
	mux.HandleFunc("GET /callback", r.Callback)
	mux.HandleFunc("POST /logout", r.Logout)
	mux.HandleFunc("POST /backchannel-logout", r.BackchannelLogout)
	mux.HandleFunc("GET /me", r.Me)
	mux.Handle("/api/", r.APIProxy())
	return mux
}

// Login starts the authorization code flow with PKCE, state and nonce.
func (r *RP) Login(w http.ResponseWriter, req *http.Request) {
	state, nonce := randomString(), randomString()
	verifier := oauth2.GenerateVerifier() // 32 random bytes, 43 chars
	f := Flow{
		State: state, Nonce: nonce, Verifier: verifier,
		ReturnTo:  safeReturnTo(req.URL.Query().Get("return_to")),
		ExpiresAt: r.now().Add(flowTTL),
	}
	if err := r.cfg.Store.PutFlow(req.Context(), f); err != nil {
		http.Error(w, "store unavailable", http.StatusServiceUnavailable)
		return
	}
	// Bind the state to this browser: a callback without this cookie fails.
	http.SetCookie(w, &http.Cookie{
		Name: flowCookie, Value: state, Path: "/", MaxAge: int(flowTTL.Seconds()),
		Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
	})
	opts := []oauth2.AuthCodeOption{
		oauth2.S256ChallengeOption(verifier), // code_challenge + method=S256
		oidc.Nonce(nonce),
	}
	if p := req.URL.Query().Get("prompt"); p == "login" || p == "consent" {
		opts = append(opts, oauth2.SetAuthURLParam("prompt", p))
	}
	http.Redirect(w, req, r.oauth.AuthCodeURL(state, opts...), http.StatusFound)
}

// Callback is the redirect_uri handler.
func (r *RP) Callback(w http.ResponseWriter, req *http.Request) {
	ctx := req.Context()
	q := req.URL.Query()
	clearCookie(w, flowCookie)

	if e := q.Get("error"); e != "" { // access_denied, login_required, ...
		r.cfg.Logger.Info("authorization error", "error", e)
		http.Error(w, "login failed: "+e, http.StatusUnauthorized)
		return
	}
	c, err := req.Cookie(flowCookie)
	if err != nil || q.Get("state") == "" ||
		subtle.ConstantTimeCompare([]byte(c.Value), []byte(q.Get("state"))) != 1 {
		http.Error(w, "state mismatch", http.StatusBadRequest) // CSRF or stale tab
		return
	}
	f, err := r.cfg.Store.TakeFlow(ctx, q.Get("state"))
	if err != nil {
		http.Error(w, "unknown or expired login attempt", http.StatusBadRequest)
		return
	}
	// RFC 9207 mix-up defence: the response names its issuer.
	switch iss := q.Get("iss"); {
	case iss != "" && iss != r.cfg.Issuer:
		http.Error(w, "issuer mismatch", http.StatusBadRequest)
		return
	case iss == "" && r.meta.IssParameter:
		http.Error(w, "missing iss", http.StatusBadRequest)
		return
	}

	tok, err := r.oauth.Exchange(ctx, q.Get("code"), oauth2.VerifierOption(f.Verifier))
	if err != nil {
		var re *oauth2.RetrieveError
		if errors.As(err, &re) { // invalid_grant: reused, expired or PKCE mismatch
			r.cfg.Logger.Warn("token endpoint error", "error", re.ErrorCode)
		}
		http.Error(w, "code exchange failed", http.StatusBadGateway)
		return
	}
	rawID, ok := tok.Extra("id_token").(string)
	if !ok {
		http.Error(w, "no id_token in token response", http.StatusBadGateway)
		return
	}
	idt, err := r.idVerifier.Verify(ctx, rawID)
	if err != nil {
		http.Error(w, "invalid id_token", http.StatusUnauthorized)
		return
	}
	if subtle.ConstantTimeCompare([]byte(idt.Nonce), []byte(f.Nonce)) != 1 {
		http.Error(w, "nonce mismatch", http.StatusUnauthorized)
		return
	}
	if idt.AccessTokenHash != "" { // at_hash is optional in the code flow
		if err := idt.VerifyAccessToken(tok.AccessToken); err != nil {
			http.Error(w, "at_hash mismatch", http.StatusUnauthorized)
			return
		}
	}
	var claims struct {
		SID string `json:"sid"`
	}
	_ = idt.Claims(&claims)

	s := &Session{
		ID: randomString(), Subject: idt.Subject, IdPSID: claims.SID,
		IDToken: rawID, Token: tok, CreatedAt: r.now(),
	}
	if err := r.cfg.Store.PutSession(ctx, s); err != nil {
		http.Error(w, "store unavailable", http.StatusServiceUnavailable)
		return
	}
	http.SetCookie(w, &http.Cookie{
		Name: sessionCookie, Value: s.ID, Path: "/", MaxAge: 8 * 3600,
		Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
	})
	http.Redirect(w, req, f.ReturnTo, http.StatusFound)
}

// Me tells the SPA who is logged in, without exposing any token.
func (r *RP) Me(w http.ResponseWriter, req *http.Request) {
	s, err := r.session(req)
	if err != nil {
		http.Error(w, "not logged in", http.StatusUnauthorized)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Cache-Control", "no-store")
	_ = json.NewEncoder(w).Encode(map[string]string{"sub": s.Subject})
}

// APIProxy forwards /api/* to the resource server with the access token,
// refreshing it first when it is about to expire.
func (r *RP) APIProxy() http.Handler {
	proxy := &httputil.ReverseProxy{
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(r.cfg.APIUpstream)
			pr.Out.Header.Del("Cookie") // the session cookie stays at the edge
		},
	}
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		s, err := r.session(req)
		if err != nil {
			http.Error(w, "not logged in", http.StatusUnauthorized)
			return
		}
		tok, err := r.freshToken(req.Context(), s)
		if err != nil {
			// invalid_grant on refresh: revoked, rotated twice, or expired.
			_ = r.cfg.Store.DeleteSession(req.Context(), s.ID)
			clearCookie(w, sessionCookie)
			http.Error(w, "session expired", http.StatusUnauthorized)
			return
		}
		out := req.Clone(req.Context())
		out.Header.Set("Authorization", "Bearer "+tok.AccessToken)
		proxy.ServeHTTP(w, out)
	})
}

// freshToken refreshes through x/oauth2 and saves a rotated refresh token.
func (r *RP) freshToken(ctx context.Context, s *Session) (*oauth2.Token, error) {
	ts := r.oauth.TokenSource(ctx, s.Token) // refreshes 10 s before expiry
	tok, err := ts.Token()
	if err != nil {
		return nil, err
	}
	if tok.AccessToken != s.Token.AccessToken {
		s.Token = tok // includes the new refresh_token when the AS rotates it
		if err := r.cfg.Store.PutSession(ctx, s); err != nil {
			return nil, err
		}
	}
	return tok, nil
}

// Logout ends the local session, then sends the browser to the OP's
// end_session_endpoint (RP-initiated logout) so the IdP session ends too.
func (r *RP) Logout(w http.ResponseWriter, req *http.Request) {
	target := r.cfg.PostLogout
	if s, err := r.session(req); err == nil {
		_ = r.cfg.Store.DeleteSession(req.Context(), s.ID)
		if r.meta.EndSession != "" {
			v := url.Values{
				"id_token_hint":            {s.IDToken},
				"post_logout_redirect_uri": {r.cfg.PostLogout},
				"client_id":                {r.cfg.ClientID},
			}
			target = r.meta.EndSession + "?" + v.Encode()
		}
	}
	clearCookie(w, sessionCookie)
	http.Redirect(w, req, target, http.StatusSeeOther)
}

// BackchannelLogout receives the OP's logout_token (a signed JWT) by POST.
func (r *RP) BackchannelLogout(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Cache-Control", "no-store")
	raw := req.PostFormValue("logout_token")
	t, err := r.idVerifier.Verify(req.Context(), raw) // sig, iss, aud, exp
	if err != nil {
		http.Error(w, "invalid logout_token", http.StatusBadRequest)
		return
	}
	var c struct {
		SID    string                     `json:"sid"`
		Nonce  *string                    `json:"nonce"`
		Events map[string]json.RawMessage `json:"events"`
	}
	if err := t.Claims(&c); err != nil || c.Nonce != nil || c.Events[backchannel] == nil ||
		(c.SID == "" && t.Subject == "") {
		http.Error(w, "not a logout token", http.StatusBadRequest)
		return
	}
	n, _ := r.cfg.Store.DeleteByIdP(req.Context(), t.Subject, c.SID)
	r.cfg.Logger.Info("back-channel logout", "sessions", n)
	w.WriteHeader(http.StatusOK)
}

func (r *RP) session(req *http.Request) (*Session, error) {
	c, err := req.Cookie(sessionCookie)
	if err != nil {
		return nil, ErrNotFound
	}
	return r.cfg.Store.GetSession(req.Context(), c.Value)
}

func randomString() string {
	b := make([]byte, 32)
	_, _ = rand.Read(b) // crypto/rand.Read never returns an error since Go 1.24
	return base64.RawURLEncoding.EncodeToString(b)
}

// safeReturnTo allows only local paths: no open redirector.
func safeReturnTo(p string) string {
	if p == "" || !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.Contains(p, `\`) {
		return "/"
	}
	return p
}

func clearCookie(w http.ResponseWriter, name string) {
	http.SetCookie(w, &http.Cookie{Name: name, Value: "", Path: "/", MaxAge: -1,
		Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
}

func contains(list []string, v string) bool {
	for _, s := range list {
		if s == v {
			return true
		}
	}
	return false
}

A fake OpenID Provider for the tests (discovery, JWKS, token endpoint that checks PKCE and rotates refresh tokens):

go
package rp

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"github.com/go-jose/go-jose/v4"
)

// fakeOP is a minimal OpenID Provider: discovery, JWKS, token endpoint with
// PKCE checking and refresh token rotation. Tests "authorize" by calling
// approve() with the parameters the RP put in the authorization URL.
type fakeOP struct {
	t             *testing.T
	srv           *httptest.Server
	key           *rsa.PrivateKey
	mu            sync.Mutex
	codes         map[string]grant // code -> grant
	refresh       map[string]bool  // live refresh tokens
	issued        int
	nonceOverride string
	accessTTL     time.Duration
}

type grant struct{ challenge, nonce, redirect string }

func newFakeOP(t *testing.T) *fakeOP {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	op := &fakeOP{t: t, key: key, codes: map[string]grant{}, refresh: map[string]bool{}, accessTTL: time.Hour}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /.well-known/openid-configuration", op.discovery)
	mux.HandleFunc("GET /jwks", op.jwks)
	mux.HandleFunc("POST /token", op.token)
	op.srv = httptest.NewServer(mux)
	t.Cleanup(op.srv.Close)
	return op
}

func (op *fakeOP) issuer() string { return op.srv.URL }

func (op *fakeOP) discovery(w http.ResponseWriter, _ *http.Request) {
	_ = json.NewEncoder(w).Encode(map[string]any{
		"issuer":                                         op.issuer(),
		"authorization_endpoint":                         op.issuer() + "/authorize",
		"token_endpoint":                                 op.issuer() + "/token",
		"jwks_uri":                                       op.issuer() + "/jwks",
		"end_session_endpoint":                           op.issuer() + "/logout",
		"response_types_supported":                       []string{"code"},
		"id_token_signing_alg_values_supported":          []string{"RS256"},
		"code_challenge_methods_supported":               []string{"S256"},
		"authorization_response_iss_parameter_supported": true,
	})
}

func (op *fakeOP) jwks(w http.ResponseWriter, _ *http.Request) {
	_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{
		Key: &op.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig",
	}}})
}

// approve plays the user clicking "Allow": it records a one-time code.
func (op *fakeOP) approve(challenge, nonce, redirect string) string {
	op.mu.Lock()
	defer op.mu.Unlock()
	code := randomString()
	op.codes[code] = grant{challenge, nonce, redirect}
	return code
}

func (op *fakeOP) token(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()
	op.mu.Lock()
	defer op.mu.Unlock()
	fail := func(code string) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		_ = json.NewEncoder(w).Encode(map[string]string{"error": code})
	}
	if id, secret, ok := r.BasicAuth(); !ok || id != "shop-bff" || secret != "s3cret" {
		if r.PostForm.Get("client_id") != "shop-bff" || r.PostForm.Get("client_secret") != "s3cret" {
			fail("invalid_client")
			return
		}
	}
	nonce := ""
	switch r.PostForm.Get("grant_type") {
	case "authorization_code":
		g, ok := op.codes[r.PostForm.Get("code")]
		delete(op.codes, r.PostForm.Get("code")) // one-time use
		sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
		if !ok || g.redirect != r.PostForm.Get("redirect_uri") ||
			base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge {
			fail("invalid_grant")
			return
		}
		nonce = g.nonce
		if op.nonceOverride != "" {
			nonce = op.nonceOverride
		}
	case "refresh_token":
		rt := r.PostForm.Get("refresh_token")
		if !op.refresh[rt] {
			fail("invalid_grant") // reused after rotation, or revoked
			return
		}
		delete(op.refresh, rt) // rotation: the old one dies now
	default:
		fail("unsupported_grant_type")
		return
	}
	op.issued++
	rt := randomString()
	op.refresh[rt] = true
	now := time.Now()
	claims := map[string]any{
		"iss": op.issuer(), "sub": "user-42", "aud": "shop-bff", "sid": "idp-sess-1",
		"iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(),
	}
	if nonce != "" {
		claims["nonce"] = nonce
	}
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Cache-Control", "no-store")
	_ = json.NewEncoder(w).Encode(map[string]any{
		"access_token":  "at-" + randomString(),
		"token_type":    "Bearer",
		"expires_in":    int(op.accessTTL.Seconds()),
		"refresh_token": rt,
		"id_token":      op.sign(claims, "JWT"),
	})
}

func (op *fakeOP) sign(claims map[string]any, typ string) string {
	signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: op.key},
		(&jose.SignerOptions{}).WithType(jose.ContentType(typ)).WithHeader("kid", "k1"))
	if err != nil {
		op.t.Fatal(err)
	}
	payload, _ := json.Marshal(claims)
	obj, err := signer.Sign(payload)
	if err != nil {
		op.t.Fatal(err)
	}
	s, _ := obj.CompactSerialize()
	return s
}

The tests: authorization URL contents, full login, every callback rejection (state, CSRF, mix-up, missing iss, injected code, nonce replay, access_denied), single-use state, refresh with rotation, back-channel logout, open-redirect guard:

go
package rp

import (
	"context"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"
)

const redirectURL = "https://app.example.com/callback"

type harness struct {
	t     *testing.T
	op    *fakeOP
	rp    *RP
	store *MemoryStore
	api   *httptest.Server
	seen  string // Authorization header the API received
}

func newHarness(t *testing.T) *harness {
	h := &harness{t: t, op: newFakeOP(t), store: NewMemoryStore()}
	h.api = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h.seen = r.Header.Get("Authorization")
		if r.Header.Get("Cookie") != "" {
			t.Error("session cookie leaked to the resource server")
		}
		w.WriteHeader(http.StatusNoContent)
	}))
	t.Cleanup(h.api.Close)
	up, _ := url.Parse(h.api.URL)
	rp, err := New(context.Background(), Config{
		Issuer: h.op.issuer(), ClientID: "shop-bff", ClientSecret: "s3cret",
		RedirectURL: redirectURL, PostLogout: "https://app.example.com/",
		Scopes: []string{"profile", "offline_access"}, APIUpstream: up, Store: h.store,
	})
	if err != nil {
		t.Fatal(err)
	}
	h.rp = rp
	return h
}

// login runs /login and returns the authorization URL and the flow cookie.
func (h *harness) login() (*url.URL, *http.Cookie) {
	rec := httptest.NewRecorder()
	h.rp.Routes().ServeHTTP(rec, httptest.NewRequest("GET", "/login?return_to=/orders", nil))
	if rec.Code != http.StatusFound {
		h.t.Fatalf("login status %d", rec.Code)
	}
	u, _ := url.Parse(rec.Header().Get("Location"))
	return u, rec.Result().Cookies()[0]
}

func (h *harness) callback(query string, c *http.Cookie) *httptest.ResponseRecorder {
	req := httptest.NewRequest("GET", "/callback?"+query, nil)
	if c != nil {
		req.AddCookie(c)
	}
	rec := httptest.NewRecorder()
	h.rp.Routes().ServeHTTP(rec, req)
	return rec
}

func TestAuthorizationURLCarriesPKCEStateNonce(t *testing.T) {
	h := newHarness(t)
	u, c := h.login()
	q := u.Query()
	for k, want := range map[string]string{
		"response_type": "code", "client_id": "shop-bff",
		"redirect_uri": redirectURL, "code_challenge_method": "S256",
	} {
		if q.Get(k) != want {
			t.Errorf("%s = %q, want %q", k, q.Get(k), want)
		}
	}
	if !strings.Contains(q.Get("scope"), "openid") {
		t.Error("scope lacks openid")
	}
	if len(q.Get("code_challenge")) != 43 || q.Get("nonce") == "" || q.Get("state") == "" {
		t.Error("missing code_challenge, nonce or state")
	}
	if c.Name != "__Host-oidc-flow" || !c.HttpOnly || !c.Secure || c.Value != q.Get("state") {
		t.Errorf("flow cookie %+v does not bind state", c)
	}
}

func TestFullLoginCreatesSession(t *testing.T) {
	h := newHarness(t)
	u, c := h.login()
	q := u.Query()
	code := h.op.approve(q.Get("code_challenge"), q.Get("nonce"), redirectURL)
	rec := h.callback(url.Values{"code": {code}, "state": {q.Get("state")}, "iss": {h.op.issuer()}}.Encode(), c)
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/orders" {
		t.Fatalf("callback = %d %s: %s", rec.Code, rec.Header().Get("Location"), rec.Body)
	}
	var sid *http.Cookie
	for _, ck := range rec.Result().Cookies() {
		if ck.Name == "__Host-sid" {
			sid = ck
		}
	}
	if sid == nil || !sid.HttpOnly || !sid.Secure || sid.SameSite != http.SameSiteLaxMode {
		t.Fatalf("session cookie missing or weak: %+v", sid)
	}
	s, err := h.store.GetSession(context.Background(), sid.Value)
	if err != nil || s.Subject != "user-42" || s.Token.RefreshToken == "" {
		t.Fatalf("session = %+v, %v", s, err)
	}
	if strings.Contains(rec.Body.String(), s.Token.AccessToken) {
		t.Fatal("access token reached the browser")
	}
}

func TestCallbackRejections(t *testing.T) {
	cases := []struct {
		name   string
		mutate func(h *harness, q url.Values, c **http.Cookie, v url.Values)
		want   int
	}{
		{"state differs from cookie", func(_ *harness, _ url.Values, _ **http.Cookie, v url.Values) { v.Set("state", "attacker") }, 400},
		{"no flow cookie (CSRF)", func(_ *harness, _ url.Values, c **http.Cookie, _ url.Values) { *c = nil }, 400},
		{"mix-up: other issuer", func(_ *harness, _ url.Values, _ **http.Cookie, v url.Values) { v.Set("iss", "https://evil.example") }, 400},
		{"iss missing although advertised", func(_ *harness, _ url.Values, _ **http.Cookie, v url.Values) { v.Del("iss") }, 400},
		{"injected code (PKCE fails)", func(h *harness, _ url.Values, _ **http.Cookie, v url.Values) {
			v.Set("code", h.op.approve("attacker-challenge", "n", redirectURL))
		}, 502},
		{"nonce replay", func(h *harness, _ url.Values, _ **http.Cookie, _ url.Values) { h.op.nonceOverride = "old-nonce" }, 401},
		{"error from AS", func(_ *harness, _ url.Values, _ **http.Cookie, v url.Values) { v.Set("error", "access_denied") }, 401},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			h := newHarness(t)
			u, c := h.login()
			q := u.Query()
			v := url.Values{
				"code":  {h.op.approve(q.Get("code_challenge"), q.Get("nonce"), redirectURL)},
				"state": {q.Get("state")}, "iss": {h.op.issuer()},
			}
			tc.mutate(h, q, &c, v)
			if rec := h.callback(v.Encode(), c); rec.Code != tc.want {
				t.Fatalf("status %d, want %d: %s", rec.Code, tc.want, rec.Body)
			}
		})
	}
}

func TestStateIsSingleUse(t *testing.T) {
	h := newHarness(t)
	u, c := h.login()
	q := u.Query()
	v := url.Values{"code": {h.op.approve(q.Get("code_challenge"), q.Get("nonce"), redirectURL)},
		"state": {q.Get("state")}, "iss": {h.op.issuer()}}
	if rec := h.callback(v.Encode(), c); rec.Code != http.StatusFound {
		t.Fatalf("first callback %d", rec.Code)
	}
	if rec := h.callback(v.Encode(), c); rec.Code != http.StatusBadRequest {
		t.Fatalf("replayed callback %d, want 400", rec.Code)
	}
}

func TestProxyRefreshesAndRotates(t *testing.T) {
	h := newHarness(t)
	h.op.accessTTL = time.Second // inside x/oauth2's 10 s early-expiry window
	u, c := h.login()
	q := u.Query()
	rec := h.callback(url.Values{"code": {h.op.approve(q.Get("code_challenge"), q.Get("nonce"), redirectURL)},
		"state": {q.Get("state")}, "iss": {h.op.issuer()}}.Encode(), c)
	sid := rec.Result().Cookies()[1]
	before, _ := h.store.GetSession(context.Background(), sid.Value)

	req := httptest.NewRequest("GET", "/api/orders", nil)
	req.AddCookie(sid)
	out := httptest.NewRecorder()
	h.rp.Routes().ServeHTTP(out, req)
	if out.Code != http.StatusNoContent {
		t.Fatalf("proxy status %d: %s", out.Code, out.Body)
	}
	after, _ := h.store.GetSession(context.Background(), sid.Value)
	if after.Token.RefreshToken == before.Token.RefreshToken || h.seen != "Bearer "+after.Token.AccessToken {
		t.Fatal("token was not refreshed, rotated and forwarded")
	}
	// The old refresh token is dead at the OP: replay gives invalid_grant.
	if h.op.refresh[before.Token.RefreshToken] {
		t.Fatal("old refresh token still valid")
	}
}

func TestBackchannelLogoutDeletesSessions(t *testing.T) {
	h := newHarness(t)
	_ = h.store.PutSession(context.Background(), &Session{ID: "s1", Subject: "user-42", IdPSID: "idp-sess-1"})
	now := time.Now()
	tok := h.op.sign(map[string]any{
		"iss": h.op.issuer(), "aud": "shop-bff", "sub": "user-42", "sid": "idp-sess-1",
		"iat": now.Unix(), "exp": now.Add(2 * time.Minute).Unix(), "jti": "j1",
		"events": map[string]any{backchannel: map[string]any{}},
	}, "logout+jwt")
	req := httptest.NewRequest("POST", "/backchannel-logout", strings.NewReader("logout_token="+tok))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	h.rp.Routes().ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status %d: %s", rec.Code, rec.Body)
	}
	if _, err := h.store.GetSession(context.Background(), "s1"); err == nil {
		t.Fatal("session survived back-channel logout")
	}
}

func TestSafeReturnTo(t *testing.T) {
	for in, want := range map[string]string{"/orders": "/orders", "//evil.example": "/", "https://evil.example": "/", `/\evil`: "/", "": "/"} {
		if got := safeReturnTo(in); got != want {
			t.Errorf("safeReturnTo(%q) = %q, want %q", in, got, want)
		}
	}
}

After: a resource server ​

Bearer extraction with RFC 6750 errors, RFC 9068 JWT validation (typ, iss, aud, exp, scope) and an RFC 7662 introspection client with a short cache:

go
// Package resource is a minimal OAuth 2.0 resource server: it accepts bearer
// tokens (RFC 6750), validates JWT access tokens (RFC 9068) locally or opaque
// tokens through introspection (RFC 7662), and enforces scopes.
package resource

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"slices"
	"strings"
	"sync"
	"time"

	"github.com/coreos/go-oidc/v3/oidc"
)

// Principal is what handlers see after validation.
type Principal struct {
	Subject  string
	ClientID string
	Scopes   []string
}

type ctxKey struct{}

// From returns the principal stored by Middleware.
func From(ctx context.Context) (Principal, bool) {
	p, ok := ctx.Value(ctxKey{}).(Principal)
	return p, ok
}

// Validator turns a raw bearer token into a principal.
type Validator interface {
	Validate(ctx context.Context, raw string) (Principal, error)
}

// ErrInvalidToken covers bad signature, wrong iss/aud, expiry, inactive.
var ErrInvalidToken = errors.New("invalid_token")

// JWTValidator checks RFC 9068 JWT access tokens with keys from the
// issuer's JWKS. Audience is this API's identifier, not a client id.
type JWTValidator struct {
	v *oidc.IDTokenVerifier
}

// NewJWTValidator builds the verifier. keys is usually
// oidc.NewRemoteKeySet(ctx, jwksURI); tests pass an oidc.StaticKeySet.
func NewJWTValidator(issuer, audience string, keys oidc.KeySet) *JWTValidator {
	return &JWTValidator{v: oidc.NewVerifier(issuer, keys, &oidc.Config{
		ClientID:             audience, // go-oidc checks aud contains this
		SupportedSigningAlgs: []string{oidc.RS256, oidc.ES256},
	})}
}

func (j *JWTValidator) Validate(ctx context.Context, raw string) (Principal, error) {
	if typ, _ := headerTyp(raw); !strings.EqualFold(typ, "at+jwt") && !strings.EqualFold(typ, "application/at+jwt") {
		// RFC 9068: reject ID tokens and other JWTs presented as access tokens.
		return Principal{}, fmt.Errorf("%w: typ %q", ErrInvalidToken, typ)
	}
	t, err := j.v.Verify(ctx, raw) // signature, iss, aud, exp
	if err != nil {
		return Principal{}, fmt.Errorf("%w: %v", ErrInvalidToken, err)
	}
	var c struct {
		ClientID string `json:"client_id"`
		Scope    string `json:"scope"`
	}
	if err := t.Claims(&c); err != nil {
		return Principal{}, fmt.Errorf("%w: %v", ErrInvalidToken, err)
	}
	return Principal{Subject: t.Subject, ClientID: c.ClientID, Scopes: strings.Fields(c.Scope)}, nil
}

func headerTyp(raw string) (string, error) {
	h, _, ok := strings.Cut(raw, ".")
	if !ok {
		return "", ErrInvalidToken
	}
	b, err := base64.RawURLEncoding.DecodeString(h)
	if err != nil {
		return "", err
	}
	var hdr struct {
		Typ string `json:"typ"`
	}
	err = json.Unmarshal(b, &hdr)
	return hdr.Typ, err
}

// Introspector validates opaque tokens by asking the authorization server
// (RFC 7662) and caches positive answers briefly.
type Introspector struct {
	Endpoint     string
	ClientID     string // the resource server authenticates itself
	ClientSecret string
	Audience     string
	TTL          time.Duration // cache lifetime: the revocation delay you accept
	HTTP         *http.Client

	mu    sync.Mutex
	cache map[string]cached
}

type cached struct {
	p   Principal
	exp time.Time
}

func (in *Introspector) Validate(ctx context.Context, raw string) (Principal, error) {
	in.mu.Lock()
	if c, ok := in.cache[raw]; ok && time.Now().Before(c.exp) {
		in.mu.Unlock()
		return c.p, nil
	}
	in.mu.Unlock()

	form := url.Values{"token": {raw}, "token_type_hint": {"access_token"}}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, in.Endpoint, strings.NewReader(form.Encode()))
	if err != nil {
		return Principal{}, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Accept", "application/json")
	req.SetBasicAuth(url.QueryEscape(in.ClientID), url.QueryEscape(in.ClientSecret))
	client := in.HTTP
	if client == nil {
		client = http.DefaultClient
	}
	resp, err := client.Do(req)
	if err != nil {
		return Principal{}, err // fail closed: the caller answers 503 or 401
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return Principal{}, fmt.Errorf("introspection: HTTP %d", resp.StatusCode)
	}
	var r struct {
		Active   bool            `json:"active"`
		Scope    string          `json:"scope"`
		ClientID string          `json:"client_id"`
		Sub      string          `json:"sub"`
		Exp      int64           `json:"exp"`
		Aud      json.RawMessage `json:"aud"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		return Principal{}, err
	}
	if !r.Active || !audienceContains(r.Aud, in.Audience) {
		return Principal{}, ErrInvalidToken
	}
	p := Principal{Subject: r.Sub, ClientID: r.ClientID, Scopes: strings.Fields(r.Scope)}
	exp := time.Now().Add(in.TTL)
	if r.Exp > 0 && time.Unix(r.Exp, 0).Before(exp) {
		exp = time.Unix(r.Exp, 0)
	}
	in.mu.Lock()
	if in.cache == nil {
		in.cache = map[string]cached{}
	}
	in.cache[raw] = cached{p, exp}
	in.mu.Unlock()
	return p, nil
}

func audienceContains(raw json.RawMessage, want string) bool {
	if want == "" {
		return true
	}
	var one string
	if json.Unmarshal(raw, &one) == nil {
		return one == want
	}
	var many []string
	return json.Unmarshal(raw, &many) == nil && slices.Contains(many, want)
}

// Middleware enforces a bearer token with every listed scope.
// Error responses follow RFC 6750 section 3.
func Middleware(v Validator, realm string, scopes ...string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Query().Has("access_token") {
				// Tokens in URLs leak through logs, history and Referer.
				challenge(w, http.StatusBadRequest, realm, `error="invalid_request"`)
				return
			}
			auth := r.Header.Get("Authorization")
			scheme, raw, ok := strings.Cut(auth, " ")
			if auth == "" {
				challenge(w, http.StatusUnauthorized, realm, "") // no error code
				return
			}
			if !ok || !strings.EqualFold(scheme, "Bearer") || raw == "" {
				challenge(w, http.StatusBadRequest, realm, `error="invalid_request"`)
				return
			}
			p, err := v.Validate(r.Context(), raw)
			if err != nil {
				challenge(w, http.StatusUnauthorized, realm, `error="invalid_token"`)
				return
			}
			for _, s := range scopes {
				if !slices.Contains(p.Scopes, s) {
					challenge(w, http.StatusForbidden, realm,
						fmt.Sprintf(`error="insufficient_scope", scope=%q`, strings.Join(scopes, " ")))
					return
				}
			}
			next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
		})
	}
}

func challenge(w http.ResponseWriter, status int, realm, params string) {
	v := fmt.Sprintf(`Bearer realm=%q`, realm)
	if params != "" {
		v += ", " + params
	}
	w.Header().Set("WWW-Authenticate", v)
	w.Header().Set("Cache-Control", "no-store")
	http.Error(w, http.StatusText(status), status)
}
go
package resource

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/coreos/go-oidc/v3/oidc"
	"github.com/go-jose/go-jose/v4"
)

const (
	issuer   = "https://id.example.com"
	audience = "https://api.example.com"
)

func sign(t *testing.T, key *rsa.PrivateKey, typ string, claims map[string]any) string {
	t.Helper()
	s, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key},
		(&jose.SignerOptions{}).WithType(jose.ContentType(typ)))
	if err != nil {
		t.Fatal(err)
	}
	b, _ := json.Marshal(claims)
	obj, err := s.Sign(b)
	if err != nil {
		t.Fatal(err)
	}
	out, _ := obj.CompactSerialize()
	return out
}

func claims(scope, aud string, exp time.Time) map[string]any {
	return map[string]any{"iss": issuer, "sub": "user-42", "aud": aud, "client_id": "shop-bff",
		"scope": scope, "iat": time.Now().Unix(), "exp": exp.Unix(), "jti": "j1"}
}

func TestJWTMiddleware(t *testing.T) {
	key, _ := rsa.GenerateKey(rand.Reader, 2048)
	other, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	v := NewJWTValidator(issuer, audience, &oidc.StaticKeySet{PublicKeys: []crypto.PublicKey{&key.PublicKey, &other.PublicKey}})
	h := Middleware(v, "orders", "orders:read")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		p, _ := From(r.Context())
		_, _ = w.Write([]byte(p.Subject))
	}))
	soon := time.Now().Add(5 * time.Minute)
	cases := []struct {
		name, auth, path string
		want             int
		wantChallenge    string
	}{
		{"valid", "Bearer " + sign(t, key, "at+jwt", claims("orders:read profile", audience, soon)), "/", 200, ""},
		{"no header", "", "/", 401, `Bearer realm="orders"`},
		{"basic scheme", "Basic abc", "/", 400, `invalid_request`},
		{"token in query", "", "/?access_token=x", 400, `invalid_request`},
		{"wrong scope", "Bearer " + sign(t, key, "at+jwt", claims("profile", audience, soon)), "/", 403, `insufficient_scope`},
		{"wrong audience", "Bearer " + sign(t, key, "at+jwt", claims("orders:read", "https://other.example", soon)), "/", 401, `invalid_token`},
		{"expired", "Bearer " + sign(t, key, "at+jwt", claims("orders:read", audience, time.Now().Add(-time.Minute))), "/", 401, `invalid_token`},
		{"ID token used as access token", "Bearer " + sign(t, key, "JWT", claims("orders:read", audience, soon)), "/", 401, `invalid_token`},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			req := httptest.NewRequest("GET", c.path, nil)
			if c.auth != "" {
				req.Header.Set("Authorization", c.auth)
			}
			rec := httptest.NewRecorder()
			h.ServeHTTP(rec, req)
			if rec.Code != c.want {
				t.Fatalf("status %d, want %d", rec.Code, c.want)
			}
			if !strings.Contains(rec.Header().Get("WWW-Authenticate"), c.wantChallenge) {
				t.Fatalf("WWW-Authenticate %q lacks %q", rec.Header().Get("WWW-Authenticate"), c.wantChallenge)
			}
		})
	}
}

func TestIntrospectorCachesAndFailsClosed(t *testing.T) {
	calls := 0
	as := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		calls++
		_ = r.ParseForm()
		if id, _, _ := r.BasicAuth(); id != "orders-api" {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		active := r.PostForm.Get("token") == "opaque-good"
		_ = json.NewEncoder(w).Encode(map[string]any{
			"active": active, "scope": "orders:read", "sub": "user-42", "aud": audience,
			"exp": time.Now().Add(time.Hour).Unix(),
		})
	}))
	defer as.Close()
	in := &Introspector{Endpoint: as.URL, ClientID: "orders-api", ClientSecret: "x", Audience: audience, TTL: 30 * time.Second}
	for i := 0; i < 3; i++ {
		if _, err := in.Validate(context.Background(), "opaque-good"); err != nil {
			t.Fatal(err)
		}
	}
	if calls != 1 {
		t.Fatalf("introspection called %d times, want 1 (cached)", calls)
	}
	if _, err := in.Validate(context.Background(), "revoked"); err == nil {
		t.Fatal("inactive token accepted")
	}
	as.Close()
	if _, err := in.Validate(context.Background(), "new-token"); err == nil {
		t.Fatal("accepted a token while the AS was down")
	}
}

Grants without a browser ​

Client credentials, device authorization and token exchange:

go
// Command machine shows the three grants that have no browser redirect:
// client credentials (service to service), the device authorization grant
// (RFC 8628, TVs and CLIs) and token exchange (RFC 8693, delegation).
// It exits unless OAUTH_ISSUER_TOKEN_URL is set, so it compiles and runs
// without an authorization server.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/clientcredentials"
)

func main() {
	tokenURL := os.Getenv("OAUTH_ISSUER_TOKEN_URL") // e.g. https://id.example.com/oauth2/token
	if tokenURL == "" {
		fmt.Println("set OAUTH_ISSUER_TOKEN_URL, CLIENT_ID, CLIENT_SECRET to run")
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	// 1. Client credentials: the client is the resource owner. No refresh
	// token is issued; the TokenSource simply asks again near expiry.
	cc := clientcredentials.Config{
		ClientID:     os.Getenv("CLIENT_ID"),
		ClientSecret: os.Getenv("CLIENT_SECRET"),
		TokenURL:     tokenURL,
		Scopes:       []string{"inventory:read"},
		// RFC 8707 resource indicator: ask for a token for one API only.
		EndpointParams: url.Values{"resource": {"https://inventory.example.com"}},
		AuthStyle:      oauth2.AuthStyleInHeader, // client_secret_basic
	}
	client := cc.Client(ctx) // attaches "Authorization: Bearer ..." itself
	_ = client

	// 2. Device authorization grant.
	dev := oauth2.Config{
		ClientID: os.Getenv("CLIENT_ID"),
		Endpoint: oauth2.Endpoint{
			DeviceAuthURL: strings.TrimSuffix(tokenURL, "/token") + "/device/code",
			TokenURL:      tokenURL,
		},
		Scopes: []string{"openid", "profile"},
	}
	da, err := dev.DeviceAuth(ctx)
	if err != nil {
		log.Fatalf("device authorization: %v", err)
	}
	fmt.Printf("Open %s and enter the code %s\n", da.VerificationURI, da.UserCode)
	// Polls every da.Interval seconds, adds 5 s on slow_down, keeps going on
	// authorization_pending, stops on access_denied or expired_token.
	tok, err := dev.DeviceAccessToken(ctx, da)
	if err != nil {
		log.Fatalf("device token: %v", err)
	}

	// 3. Token exchange: an API that received the user's token asks for a
	// narrower token to call the next API on the user's behalf.
	down, err := exchange(ctx, tokenURL, cc.ClientID, cc.ClientSecret, tok.AccessToken, "https://billing.example.com")
	if err != nil {
		log.Fatalf("token exchange: %v", err)
	}
	fmt.Println("downstream token type:", down.IssuedTokenType)
}

// ExchangeResponse is the RFC 8693 section 2.2.1 response.
type ExchangeResponse struct {
	AccessToken     string `json:"access_token"`
	IssuedTokenType string `json:"issued_token_type"`
	TokenType       string `json:"token_type"`
	ExpiresIn       int    `json:"expires_in"`
	Scope           string `json:"scope"`
}

func exchange(ctx context.Context, tokenURL, id, secret, subjectToken, audience string) (*ExchangeResponse, error) {
	form := url.Values{
		"grant_type":           {"urn:ietf:params:oauth:grant-type:token-exchange"},
		"subject_token":        {subjectToken},
		"subject_token_type":   {"urn:ietf:params:oauth:token-type:access_token"},
		"requested_token_type": {"urn:ietf:params:oauth:token-type:access_token"},
		"audience":             {audience},
		"scope":                {"invoices:read"},
		// For delegation (not impersonation) also send actor_token and
		// actor_token_type; the new token then carries an "act" claim.
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.SetBasicAuth(url.QueryEscape(id), url.QueryEscape(secret))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		var e struct {
			Error string `json:"error"` // invalid_request, invalid_target, ...
		}
		_ = json.NewDecoder(resp.Body).Decode(&e)
		return nil, fmt.Errorf("HTTP %d %s", resp.StatusCode, e.Error)
	}
	var out ExchangeResponse
	return &out, json.NewDecoder(resp.Body).Decode(&out)
}

The Go angle ​

  • golang.org/x/oauth2 (v0.38.0 here): Config.AuthCodeURL, Exchange, TokenSource (a ReuseTokenSource that refreshes 10 seconds before expiry and keeps a rotated refresh token), GenerateVerifier, S256ChallengeOption, VerifierOption, DeviceAuth and DeviceAccessToken (which follows interval and adds 5 s on slow_down), and *oauth2.RetrieveError whose ErrorCode is RFC 6749's error (invalid_grant, invalid_client). The clientcredentials subpackage handles the machine grant.
  • github.com/coreos/go-oidc/v3/oidc (v3.21.0): NewProvider does discovery and checks that the document's issuer equals the URL; Provider.Verifier(&oidc.Config{ClientID}) checks signature (JWKS cached by RemoteKeySet), iss, aud, exp; you check Nonce yourself, and VerifyAccessToken for at_hash. Provider.Claims reads extra metadata such as end_session_endpoint. NewVerifier with StaticKeySet is handy in tests, and with a remote key set and ClientID set to the API audience it validates JWT access tokens (add the typ: at+jwt check yourself, as resource.go does).
  • go-oidc does not run an OP. To be an authorization server in Go, use Ory Hydra or Dex (both Go) rather than hand-writing one; pkce.Verify shows only the check every AS performs.
  • Concurrency: two simultaneous requests for one session can both refresh; with rotation the second gets invalid_grant. Production code wraps freshToken in a per-session lock or golang.org/x/sync/singleflight.
  • Dependencies force the module's go directive to 1.26.0 (go-oidc v3.21.0 and x/oauth2 v0.38.0 with Go 1.27 tooling); pkce alone is stdlib plus x/oauth2 for the cross-check test.

Laravel ​

Example: Passport as the authorization server ​

Install with php artisan install:api --passport (migrations and keys), add the HasApiTokens trait and OAuthenticatable interface to User, and set the api guard's driver to passport:

php
<?php

// Excerpt of config/auth.php: the "api" guard validates Passport tokens.
return [
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
];

Scopes, default scopes, token lifetimes and the consent and device views:

php
<?php

namespace App\Providers;

use Carbon\CarbonInterval;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Scopes are what a client may ask for; the consent screen shows the
        // descriptions. Permissions inside the API are a separate check.
        Passport::tokensCan([
            'user:read' => 'Read your profile',
            'orders:read' => 'See your orders',
            'orders:create' => 'Place orders for you',
            'inventory:read' => 'Read stock levels (service clients)',
        ]);

        // A client that asks for no scope gets the least useful token.
        Passport::defaultScopes(['user:read']);

        // Passport's default access token lifetime is one year. Shorten it:
        // revocation then matters less, and refresh tokens carry the session.
        Passport::tokensExpireIn(CarbonInterval::minutes(15));
        Passport::refreshTokensExpireIn(CarbonInterval::days(30));
        Passport::personalAccessTokensExpireIn(CarbonInterval::months(1));

        // The consent page for the authorization code grant.
        Passport::authorizationView('auth.oauth.authorize');

        // Device grant pages (RFC 8628): enter the user_code, then approve.
        Passport::deviceUserCodeView('auth.oauth.device.user-code');
        Passport::deviceAuthorizationView('auth.oauth.device.authorize');
    }
}

Resource routes with CheckToken, CheckTokenForAnyScope and EnsureClientIsResourceOwner:

php
<?php

use App\Http\Controllers\OrderController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Http\Middleware\CheckToken;
use Laravel\Passport\Http\Middleware\CheckTokenForAnyScope;
use Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner;

// User tokens (authorization code + PKCE): auth:api uses Passport's guard.
Route::middleware('auth:api')->group(function () {
    // Every listed scope is required.
    Route::get('/orders', [OrderController::class, 'index'])
        ->middleware(CheckToken::using('orders:read'));

    Route::post('/orders', [OrderController::class, 'store'])
        ->middleware(CheckToken::using('orders:read', 'orders:create'));

    // Any one of the listed scopes is enough.
    Route::get('/me', function (Request $request) {
        // Scope says the client may ask; the policy says the user may do it.
        abort_unless($request->user()->tokenCan('user:read'), 403);

        return $request->user()->only(['id', 'name']);
    })->middleware(CheckTokenForAnyScope::using('user:read', 'orders:read'));
});

// Machine tokens (client credentials): no user; the client owns itself.
Route::get('/inventory', fn () => ['sku-1' => 12])
    ->middleware(EnsureClientIsResourceOwner::using('inventory:read'));

Example: a Laravel app as client, Socialite login ​

Socialite provider configuration:

php
<?php

// Excerpt of config/services.php for Socialite. Secrets come from .env;
// redirect URIs must equal what is registered at the provider, byte for byte.
return [
    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => '/auth/github/callback',
    ],

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => '/auth/google/callback',
    ],
];

Social login routes (linking by provider id, hd verified after login, session regenerated) and the PKCE client routes:

php
<?php

use App\Http\Controllers\PassportPkceClientController;
use App\Models\SocialAccount;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Laravel\Socialite\Socialite;

// Social login with Socialite. Socialite stores a random state in the
// session on redirect() and checks it in user(): InvalidStateException
// on mismatch. Do not use stateless() for browser logins.
Route::get('/auth/{provider}/redirect', function (string $provider) {
    abort_unless(in_array($provider, ['github', 'google'], true), 404);

    $driver = Socialite::driver($provider);

    if ($provider === 'google') {
        // hd is a hint for the account chooser only: verify it after login.
        $driver = $driver->with(['hd' => 'example.com', 'prompt' => 'select_account']);
    }

    return $driver->redirect();
})->name('social.redirect');

Route::get('/auth/{provider}/callback', function (Request $request, string $provider) {
    abort_unless(in_array($provider, ['github', 'google'], true), 404);

    $remote = Socialite::driver($provider)->user();

    if ($provider === 'google' && ($remote->user['hd'] ?? null) !== 'example.com') {
        abort(403, 'Use your company account.');
    }

    // Link by (provider, provider_user_id), never by email alone: an email
    // at a provider may be unverified or reassigned.
    $user = DB::transaction(function () use ($provider, $remote) {
        $account = SocialAccount::firstWhere([
            'provider' => $provider,
            'provider_user_id' => (string) $remote->getId(),
        ]);

        if ($account !== null) {
            return $account->user;
        }

        $user = User::create([
            'name' => $remote->getName() ?? $remote->getNickname() ?? 'user',
            'email' => $remote->getEmail(),
        ]);

        $user->socialAccounts()->create([
            'provider' => $provider,
            'provider_user_id' => (string) $remote->getId(),
            // Store provider tokens only if you call the provider's API later.
            'refresh_token' => $remote->refreshToken !== null ? encrypt($remote->refreshToken) : null,
        ]);

        return $user;
    });

    Auth::login($user);
    $request->session()->regenerate(); // new session id after login

    return redirect()->intended('/dashboard');
})->name('social.callback');

// This app as an OAuth client of a Passport server, with PKCE.
Route::get('/connect/redirect', [PassportPkceClientController::class, 'redirect']);
Route::get('/connect/callback', [PassportPkceClientController::class, 'callback']);
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('social_accounts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('provider', 32);          // github, google, keycloak
            $table->string('provider_user_id');      // the IdP's stable "sub"
            $table->text('refresh_token')->nullable(); // encrypted, optional
            $table->timestamps();
            $table->unique(['provider', 'provider_user_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('social_accounts');
    }
};

A Laravel app consuming a Passport server with PKCE (php artisan passport:client --public):

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

/**
 * A Laravel app acting as a public OAuth client of a Passport server
 * (created with `php artisan passport:client --public`).
 */
class PassportPkceClientController extends Controller
{
    private const AUTHORIZE = 'https://id.example.com/oauth/authorize';

    private const TOKEN = 'https://id.example.com/oauth/token';

    private const REDIRECT = 'https://app.example.com/connect/callback';

    public function redirect(Request $request): RedirectResponse
    {
        $state = Str::random(40);
        $verifier = Str::random(128); // 43-128 unreserved characters

        $request->session()->put('oauth.state', $state);
        $request->session()->put('oauth.verifier', $verifier);

        $challenge = strtr(rtrim(base64_encode(hash('sha256', $verifier, true)), '='), '+/', '-_');

        return redirect(self::AUTHORIZE.'?'.http_build_query([
            'client_id' => config('services.passport.client_id'),
            'redirect_uri' => self::REDIRECT,
            'response_type' => 'code',
            'scope' => 'user:read orders:read',
            'state' => $state,
            'code_challenge' => $challenge,
            'code_challenge_method' => 'S256',
        ]));
    }

    public function callback(Request $request): RedirectResponse
    {
        // pull(): each state and verifier is usable exactly once.
        $state = $request->session()->pull('oauth.state');
        $verifier = $request->session()->pull('oauth.verifier');

        if ($request->filled('error')) {
            return redirect('/')->withErrors(['oauth' => $request->string('error')->toString()]);
        }

        abort_unless(is_string($state) && hash_equals($state, (string) $request->query('state')), 400, 'state mismatch');

        $response = Http::asForm()->timeout(5)->post(self::TOKEN, [
            'grant_type' => 'authorization_code',
            'client_id' => config('services.passport.client_id'),
            'redirect_uri' => self::REDIRECT,
            'code_verifier' => $verifier,
            'code' => $request->query('code'),
        ]);

        if ($response->failed()) {
            // invalid_grant: code reused, expired, wrong redirect_uri or verifier.
            abort(502, 'token endpoint: '.$response->json('error', 'unknown'));
        }

        // Keep tokens server-side; the browser only has the session cookie.
        $request->session()->put('oauth.tokens', encrypt($response->json()));

        return redirect('/dashboard');
    }
}

Feature tests with Passport::actingAs and actingAsClient:

php
<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Passport\Client;
use Laravel\Passport\Passport;
use Tests\TestCase;

class OAuthScopesTest extends TestCase
{
    use RefreshDatabase;

    public function test_token_with_scope_reads_orders(): void
    {
        Passport::actingAs(User::factory()->create(), ['orders:read']);

        $this->getJson('/api/orders')->assertOk();
    }

    public function test_token_without_create_scope_cannot_place_orders(): void
    {
        Passport::actingAs(User::factory()->create(), ['orders:read']);

        $this->postJson('/api/orders', ['sku' => 'sku-1'])->assertForbidden();
    }

    public function test_machine_client_reads_inventory(): void
    {
        Passport::actingAsClient(Client::factory()->create(), ['inventory:read']);

        $this->getJson('/api/inventory')->assertOk();
    }

    public function test_callback_rejects_forged_state(): void
    {
        $this->withSession(['oauth.state' => 'expected', 'oauth.verifier' => str_repeat('a', 43)])
            ->get('/connect/callback?code=x&state=attacker')
            ->assertStatus(400);
    }
}

The tables behind Passport and the BFF, with the single-use flow query and back-channel delete:

sql
-- What an authorization server stores (PostgreSQL DDL equivalent of the
-- Laravel Passport 13 migrations), plus the BFF's own session table.

-- Registered clients. Public clients (SPA, mobile, CLI) have secret IS NULL.
CREATE TABLE oauth_clients (
    id            uuid PRIMARY KEY,
    owner_type    varchar(255),           -- nullableMorphs('owner')
    owner_id      bigint,
    name          varchar(255) NOT NULL,
    secret        varchar(255),           -- hashed; NULL = public client
    provider      varchar(255),           -- which user provider
    redirect_uris text NOT NULL,          -- JSON array, compared exactly
    grant_types   text NOT NULL,          -- JSON array: authorization_code, refresh_token, ...
    revoked       boolean NOT NULL,
    created_at    timestamp,
    updated_at    timestamp
);

-- One-time authorization codes (short-lived, single use).
CREATE TABLE oauth_auth_codes (
    id         char(80) PRIMARY KEY,
    user_id    bigint NOT NULL,
    client_id  uuid NOT NULL,
    scopes     text,
    revoked    boolean NOT NULL,
    expires_at timestamp
);
CREATE INDEX ON oauth_auth_codes (user_id);

-- Access tokens: Passport issues signed tokens and keeps a row per token id
-- so it can revoke them; expires_at is informational.
CREATE TABLE oauth_access_tokens (
    id         char(80) PRIMARY KEY,      -- the token's jti
    user_id    bigint,                    -- NULL for client_credentials
    client_id  uuid NOT NULL,
    name       varchar(255),
    scopes     text,
    revoked    boolean NOT NULL,
    created_at timestamp,
    updated_at timestamp,
    expires_at timestamp
);
CREATE INDEX ON oauth_access_tokens (user_id);

CREATE TABLE oauth_refresh_tokens (
    id              char(80) PRIMARY KEY,
    access_token_id char(80) NOT NULL,
    revoked         boolean NOT NULL,
    expires_at      timestamp
);
CREATE INDEX ON oauth_refresh_tokens (access_token_id);

-- RFC 8628 device codes.
CREATE TABLE oauth_device_codes (
    id               char(80) PRIMARY KEY, -- device_code
    user_id          bigint,
    client_id        uuid NOT NULL,
    user_code        char(8) NOT NULL UNIQUE,
    scopes           text NOT NULL,
    revoked          boolean NOT NULL,
    user_approved_at timestamp,
    last_polled_at   timestamp,            -- enforces interval / slow_down
    expires_at       timestamp
);

-- The BFF side (the Go rp package): pending logins and sessions.
CREATE TABLE oidc_login_flows (
    state      text PRIMARY KEY,           -- random, bound to a cookie
    nonce      text NOT NULL,
    verifier   text NOT NULL,              -- PKCE code_verifier, never sent to the browser
    return_to  text NOT NULL DEFAULT '/',
    expires_at timestamptz NOT NULL
);

CREATE TABLE bff_sessions (
    id            text PRIMARY KEY,        -- store sha256(cookie value) in production
    subject       text NOT NULL,           -- ID token sub (with iss = the user key)
    issuer        text NOT NULL,
    idp_sid       text,                    -- for back-channel logout by sid
    id_token      text NOT NULL,           -- for id_token_hint
    access_token  text NOT NULL,           -- encrypt at rest
    refresh_token text,                    -- encrypt at rest; rotated
    expires_at    timestamptz NOT NULL,
    created_at    timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON bff_sessions (issuer, subject);
CREATE INDEX ON bff_sessions (idp_sid);

-- Take a flow exactly once (the TakeFlow of the Go store):
DELETE FROM oidc_login_flows
WHERE state = $1 AND expires_at > now()
RETURNING nonce, verifier, return_to;

-- Back-channel logout: drop every session of one IdP session.
DELETE FROM bff_sessions WHERE issuer = $1 AND idp_sid = $2;

-- Housekeeping, like `php artisan passport:purge`:
DELETE FROM oauth_access_tokens WHERE revoked OR expires_at < now() - interval '7 days';

The Laravel angle ​

  • Passport or Sanctum: the docs say "If your application absolutely needs to support OAuth2, then you should use Laravel Passport", and recommend Sanctum for authenticating your own SPA, mobile app or simple API tokens. Sanctum's SPA mode is a BFF-style cookie session; Passport is for third-party clients and machine clients.
  • Grants in Passport 13: authorization code (with consent view Passport::authorizationView), PKCE (passport:client --public), device (passport:client --device, /oauth/device/code), client credentials (passport:client --client), refresh; password and implicit are documented with "We no longer recommend".
  • Lifetimes: "By default, Passport issues long-lived access tokens that expire after one year"; set tokensExpireIn, refreshTokensExpireIn. The docs note the expires_at columns are informational; the expiry lives inside the signed token, so revoke with $token->revoke() and $token->refreshToken?->revoke(), and clean up with php artisan passport:purge.
  • Scope middleware: CheckToken::using(...) needs all scopes, CheckTokenForAnyScope::using(...) any one; $request->user()->tokenCan('orders:create') inside code; EnsureClientIsResourceOwner for client credentials tokens. Scopes are not permissions: keep policies and gates.
  • Passport is not an OpenID Provider out of the box (no ID token, discovery or logout specs); for SSO across apps use Keycloak, Auth0, Okta, Entra ID or Cognito and let Laravel be a client.
  • Socialite: Socialite::driver('github')->redirect() stores state in the session and ->user() checks it (InvalidStateException on mismatch); ->scopes([...]), ->setScopes([...]), ->with(['hd' => 'example.com']) (never pass state or response_type through with), ->stateless() only for APIs without sessions. Other IdPs (Keycloak, Okta, Entra ID) come from the community Socialite Providers.
  • Testing: Passport::actingAs($user, ['orders:read']) and Passport::actingAsClient($client, [...]).

Solving the classic problems ​

"Random logouts" with refresh token rotation ​

CauseCheckFix
Two tabs or parallel requests refresh at onceAS logs show reuse detection, invalid_grantOne refresh per session (lock, singleflight); reuse interval at the AS
Rotated token not savedSession store write after refresh failedSave atomically before returning the new access token
Refresh token idle timeoutKeycloak "SSO Session Idle" shorter than user idle timeAlign with product needs; offline_access for long sessions
IdP session ended (logout elsewhere)Back-channel logout receivedExpected: re-login

Callback errors: state mismatch, InvalidStateException ​

SymptomCauseFix
Works in Chrome, fails in SafariFlow cookie SameSite=Strict dropped on the cross-site redirect backUse Lax for the flow cookie
Fails behind the load balancerSession stored on one instanceShared session store (sessions)
Fails after a long time on the login pageFlow TTL expiredRestart login gracefully
Fails with form_postLax cookies are not sent on cross-site POSTUse query response mode, or SameSite=None; Secure for the flow cookie only
Fails on www vs apex hostCookie set on a different hostOne canonical host, redirect before login

invalid_grant at the token endpoint ​

CauseFix
Code used twice (browser retry, double click, prefetch)Treat as restart; never retry the exchange
redirect_uri differs from the authorization requestUse one constant
Code older than its lifetime (slow user agent, clock skew)Exchange immediately; check NTP
PKCE verifier lost (session lost between redirect and callback)Store the verifier server-side with the state
Refresh token revoked or rotatedDrop the session, log in again

Tokens leak into logs, Referer and analytics ​

LeakFix
Access token in a query stringHeader only; reject access_token query parameter (the Go RS returns 400)
Code in access logs of the callbackRedact code and state in NGINX/Envoy log formats
Callback page loads third-party scriptsRedirect immediately after the callback; Referrer-Policy: no-referrer
Implicit tokens in the URL fragmentMove to code + PKCE or BFF
Tokens in error reports (Sentry)Scrub Authorization, id_token, refresh_token fields

Account takeover through social login ​

CauseFix
Linking by email from an IdP that does not verify emailsLink by (iss, sub); require email_verified and a confirmation for existing accounts
Accepting any Entra ID / Google tenantAllow-list tid or verify hd in the token
ID token for another client acceptedCheck aud (and azp)
Mix-up between two IdPsCheck iss; one redirect URI per IdP

Choosing ​

Who is the resource owner?A user is presentNo user: the client itselfCan the device show a browser?Server-side web app or SPACode + PKCE via BFFNative / mobileCode + PKCE, RFC 8252TV, CLI, IoTDevice grant, RFC 8628yes: webyes: appno browserService calls an APIOwn identityClient credentialsOn behalf of a userToken exchange, RFC 8693Not any more: implicit grant (tokens in the URL fragment) and resource owner password grantRFC 9700: password grant MUST NOT be used; implicit SHOULD NOT; OAuth 2.1 removes both
SituationRecommendationExtra techniqueReason
Server-rendered web appAuthorization code + PKCE, confidential clientprivate_key_jwt, back-channel logoutTokens stay on the server
SPA with your own backendBFF (RFC 10017 pattern 1)__Host- cookie, CSRF defence, proxy /apiNo tokens in JavaScript
SPA without any backendCode + PKCE in the browserRefresh rotation or DPoP, tokens in a Web WorkerLeast secure acceptable pattern
Mobile / desktop appCode + PKCE via system browser (RFC 8252)Claimed https redirect, keychain storageWeb views are forbidden
CLICode + PKCE on a loopback port, or device grantShort-lived tokensNo browser in SSH sessions
TV, console, IoTDevice authorization grantShow client name, rate-limit pollingNo keyboard
Service to serviceClient credentialsmTLS or private_key_jwt, resourceNo user
API calling API for a userToken exchangeact claim, narrow audience, 60 s TTLLeast privilege, audit
Banking / high-valueFAPI 2.0: PAR + PKCE + sender-constrained tokensOpaque + introspectionRegulation, replay resistance
Enterprise customers with SAMLBroker (Keycloak, Auth0, Cognito)Per-tenant IdP configApps speak only OIDC
Login for your own Laravel appSanctum or session auth; Passport only if third parties need OAuthSocialite for social loginSimplicity

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith with session login does not need OAuth for its own pages. OAuth enters when (a) users log in with Google/GitHub (Socialite: the monolith is a client), or (b) third parties or a mobile app need API access (Passport: the monolith is AS and RS together). The simplest correct setup: Socialite with state, link by provider id, session()->regenerate(); Passport with PKCE public clients, short access tokens, scopes plus policies.

Modular monolith: boundaries without the network ​

Modules read the current principal (user id, tenant id, scopes) through one interface, never the token or the Socialite object. Identity is its own module that owns the social_accounts table and the Passport tables; other modules depend on CurrentPrincipal. When the identity module later becomes Keycloak, only that module changes. Example: billing calls Principal::tenantId(); it does not know whether the login came from GitHub or SAML.

Microservices: every arrow is a decision ​

An external IdP (Keycloak, Okta, Entra ID) is the only place that sees passwords. A BFF or API gateway at the edge is the OAuth client; services are resource servers that validate JWTs locally (cached JWKS) with their own audience. Service-to-service calls use client credentials or token exchange, never the user's original token forwarded blindly. See API Gateway & BFF and mTLS.

 1  browser -> edge BFF        cookie __Host-sid
 2  BFF -> orders              Bearer AT (aud=orders, scope=orders:read, sub=42, 5 min)
 3  orders -> AS               token exchange -> AT' (aud=billing, act=orders, 60 s)
 4  orders -> billing          Bearer AT'
 5  reporting-job -> AS        client_credentials scope=orders:read -> AT'' (sub=reporting-job)
 6  AS -> BFF                  back-channel logout -> BFF drops sessions; service tokens die within TTL

Distributed data: replicas, caches, regions ​

The IdP is a stateful system: users, sessions, refresh tokens, signing keys. Keycloak clusters keep authentication and user sessions in Infinispan caches; multi-region needs either region-local IdP clusters with replicated users or a SaaS IdP with global presence. Resource servers cache JWKS and keep working through a short IdP outage (JWT validation is local), but logins and refreshes stop; plan circuit breakers and longer access tokens as a degraded mode only with care. Key rotation: publish the new key in JWKS before signing with it, keep the old one until all tokens it signed expired. Introspection results in a cache are a deliberate staleness window. The BFF session store has the same replica-lag and failover issues as any session store.

Scaling path: 1x, 10x, 100x ​

ScaleDesignWhy
1x (one app)Socialite login; Passport only if third parties need API accessFewest moving parts
10x (several apps, one company)One OIDC provider (Keycloak or SaaS), SSO, BFF per front end, JWT access tokens, back-channel logoutOne login and one offboarding switch
100x (many services, many tenants)IdP cluster or SaaS per region, per-tenant issuers or Organizations, token exchange inside, introspection or phantom tokens at the edge, PAR/DPoP for sensitive clientsLeast privilege per hop, tenant isolation, replay resistance
RegulatedFAPI 2.0 profile, certified OP, mTLS everywhereCompliance and audit

Lab ​

Steps 1 and 2 run on this machine; steps 3 to 6 are expected, not run (no IdP containers).

  1. Run the Go tests (real run, in-process fake OP):
cd docs/snippets/system-design/oauth2-oidc-sso/go
go test ./... -v -run 'Callback|PKCE|Refresh|Backchannel'
# --- PASS: TestCallbackRejections/state_differs_from_cookie
# --- PASS: TestCallbackRejections/no_flow_cookie_(CSRF)
# --- PASS: TestCallbackRejections/mix-up:_other_issuer
# --- PASS: TestCallbackRejections/injected_code_(PKCE_fails)
# --- PASS: TestCallbackRejections/nonce_replay
# --- PASS: TestProxyRefreshesAndRotates
# --- PASS: TestBackchannelLogoutDeletesSessions
# ok  academy/oauth2-oidc-sso/rp
  1. Check the RFC 7636 vector by hand (real run):
printf 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '='
# E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  1. Read a provider's discovery document (expected, not run):
curl -s https://accounts.google.com/.well-known/openid-configuration | jq '{issuer, authorization_endpoint, token_endpoint, jwks_uri, code_challenge_methods_supported}'
# { "issuer": "https://accounts.google.com", ..., "code_challenge_methods_supported": ["plain","S256"] }   (checked 2026-11-26)
  1. Device grant against a Keycloak realm (expected, not run):
curl -s -d client_id=tv-app -d scope=openid https://id.example.com/realms/shop/protocol/openid-connect/auth/device
# {"device_code":"...","user_code":"WDJB-MJHT","verification_uri":".../device","expires_in":600,"interval":5}
curl -s -d grant_type=urn:ietf:params:oauth:grant-type:device_code -d client_id=tv-app -d device_code=... \
  https://id.example.com/realms/shop/protocol/openid-connect/token
# {"error":"authorization_pending","error_description":"The authorization request is still pending"}
  1. Replay a used code (expected, not run):
curl -s -u shop-bff:secret -d grant_type=authorization_code -d code=SAME_CODE -d redirect_uri=https://app.example.com/callback -d code_verifier=... https://id.example.com/token
# {"error":"invalid_grant","error_description":"Code not valid"}
  1. Laravel (expected, not run):
php artisan install:api --passport
php artisan passport:client --public        # PKCE client: prints the client id, no secret
php artisan test --filter=OAuthScopesTest
#   PASS  Tests\Feature\OAuthScopesTest  (4 tests)

Common misconceptions ​

BeliefReality
OAuth is authenticationIt is delegated authorization; OIDC adds authentication with the ID token
An access token proves who the user isIt proves a client may call an API; use the ID token, checked for aud and nonce
PKCE is only for mobileRequired for public clients (RFC 9700) and for all code flows in OAuth 2.1
state can be constantIt must be random, single-use and bound to the browser, or login CSRF works
The password grant is fine for first-party appsRFC 9700: MUST NOT be used; no MFA, phishing training
Implicit is the SPA flowDeprecated; use a BFF or code + PKCE
Wildcard redirect URIs are convenient and safeExact matching is required; wildcards meet subdomain takeovers and open redirectors
Revoking a JWT access token stops itOnly if the RS introspects or checks a denylist; otherwise it lives until exp
Scopes are permissionsScopes limit the client; permissions are your API's policy
Email is a good user keyUse (iss, sub); emails change and may be unverified
SSO means one shared cookieEach app has its own session; the IdP session is what is shared
Deleting the app cookie is logoutThe IdP session remains; use RP-initiated and back-channel logout
hd / common endpoint restricts tenantsVerify hd or tid in the token yourself
Laravel Passport is an SSO providerIt is an OAuth 2.0 server; no OIDC SSO, discovery or logout specs

Cheat sheet ​

TopicRemember
Default flowAuthorization code + PKCE (S256), state, nonce, check iss
Browser appsBFF first, tokens server-side, __Host- HttpOnly SameSite=Lax cookie
Native appsSystem browser, claimed https or loopback redirect, PKCE
MachinesClient credentials, no refresh token, cache until near expiry
TVs / CLIsDevice grant: interval 5 s, +5 s on slow_down
Dead grantsImplicit (SHOULD NOT), password (MUST NOT), both gone in OAuth 2.1
Redirect URIsExact string match; no open redirectors
Code10 minutes max, one use, bound to client + redirect_uri + verifier
ID token checksSignature (JWKS), iss, aud, exp, nonce, azp, auth_time/acr when required
Access token at RStyp at+jwt, iss, aud, exp, scope; 401 invalid_token, 403 insufficient_scope
Refresh tokensRotate with reuse detection or sender-constrain; serialize refreshes
RevocationRFC 7009 returns 200 even for unknown tokens; JWTs need short TTL
LogoutRP-initiated + back-channel; front-channel breaks without third-party cookies
HardeningPAR, JAR, DPoP or mTLS-bound tokens; FAPI 2.0 for banking
Downstream callsToken exchange with act, narrow aud, short TTL
TenantsAllow-list issuers; check tid/hd/org claims

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What are the four OAuth roles, and which one does Laravel Passport play? Must-know ​

Answer

Answer: Resource owner, client, authorization server, resource server. Passport makes a Laravel app the authorization server, and with the auth:api guard the same app is usually also the resource server.

2 — Why does a confidential client still use PKCE? Important ​

Answer

Answer: RFC 9700 recommends it for confidential clients because it protects against authorization code injection and misuse: an attacker who injects a stolen code into the client's session cannot redeem it without the verifier that belongs to that session.

3 — What exactly is code_challenge for S256, and what does the AS return when the verifier does not match? Important ​

Answer

Answer: BASE64URL without padding of SHA-256 over the ASCII verifier. A mismatch at the token endpoint is invalid_grant.

4 — An attacker sends a victim a link to your callback with the attacker's own code. Which check stops it, and what must it be bound to? Important ​

Answer

Answer: The state check (and PKCE): the state must be random, single-use and bound to the victim's browser (a cookie or server session). The victim has no matching flow, so the callback fails.

5 — What does the RFC 9207 iss parameter prevent, and when must the client require it? Good to know ​

Answer

Answer: Mix-up attacks, where a client that uses several authorization servers sends a code to the wrong one. The client must require it when the AS advertises authorization_response_iss_parameter_supported.

6 — Name five checks a relying party performs on an ID token. Must-know ​

Answer

Answer: Signature with the OP's JWKS and an expected algorithm, iss exact match, aud contains the client id (and azp if there are several audiences), exp in the future, nonce equal to the one sent; also auth_time against max_age and acr when required.

7 — Why can't you reliably revoke a JWT access token, and what are the two usual answers? Must-know ​

Answer

Answer: The resource server validates it locally and never asks the AS. Answers: short lifetimes with refresh tokens (revocable), or opaque tokens with introspection (with a short cache).

8 — What happens at the AS when a rotated refresh token is presented a second time? Important ​

Answer

Answer: It is refused with invalid_grant, and an AS with reuse detection revokes the whole token family, so both thief and client must log in again.

9 — Why does front-channel logout fail in modern browsers, and what replaces it? Good to know ​

Answer

Answer: It relies on iframes to each RP carrying the RP's cookies, which are third-party cookies and are blocked or partitioned. Back-channel logout, where the OP posts a signed logout token to each RP server, does not need the browser.

10 — A SaaS uses Entra ID's multi-tenant endpoint. What must it check so that any Microsoft tenant cannot log in? Important ​

Answer

Answer: The tenant claim (tid) or issuer against an allow-list of customer tenants, then map it to the internal tenant.

11 — What is the difference between impersonation and delegation in RFC 8693? Good to know ​

Answer

Answer: With impersonation the new token is simply the subject; the acting service is invisible. With delegation the actor keeps its own identity, expressed in the act claim, so downstream services and audit logs see "user 42 via orders-api".

12 — Why is a BFF more secure than tokens in localStorage even though XSS can still call the API? Must-know ​

Answer

Answer: XSS under a BFF can only act while the page is open and through the BFF's routes; it cannot exfiltrate long-lived refresh tokens for use elsewhere, later, at full scope.

Glossary ​

TermMeaning
OAuth 2.0Delegated authorization framework, RFC 6749
OAuth 2.1Internet-Draft consolidating OAuth 2.0 with best practices (PKCE required, implicit and password removed)
Resource ownerThe entity that can grant access to its resources
ClientApplication requesting access; public or confidential
Authorization server (AS)Issues tokens after authenticating the owner and getting consent
Resource server (RS)API that accepts access tokens
OpenID Provider (OP) / IdPOIDC authorization server that also authenticates users
Relying Party (RP) / SPApplication that relies on the IdP's identity statement (SP in SAML)
Authorization codeShort-lived, one-time code redeemed at the token endpoint
PKCEProof Key for Code Exchange, RFC 7636
code_verifier / code_challengeSecret random string / its S256 hash sent first
S256PKCE method: BASE64URL(SHA256(verifier))
Client credentialsGrant where the client acts for itself
Device authorization grantRFC 8628 flow with device_code and user_code
Refresh tokenCredential to get new access tokens from the AS
Refresh token rotationNew refresh token per use; reuse is detected as theft
Implicit grantDeprecated flow returning tokens in the URL fragment
Password grantDeprecated grant where the client collects the user's password
redirect_uriRegistered callback; must match exactly
Open redirectorEndpoint forwarding to an arbitrary URL from a parameter
stateOpaque CSRF value bound to the user agent
nonceOIDC value binding the ID token to the authentication request
iss response parameterRFC 9207 issuer in the authorization response, stops mix-up attacks
Mix-up attackClient sends a code or token to the wrong authorization server
Authorization code injectionAttacker gets a stolen code redeemed in the victim's session
ScopeSpace-delimited strings limiting what the client may ask for
ClaimName/value statement in a token or UserInfo
Access tokenCredential for the resource server; opaque or JWT
Bearer tokenToken usable by whoever holds it (RFC 6750)
at+jwtRFC 9068 typ for JWT access tokens
ID tokenSigned JWT about the authentication, for the client
azp, at_hash, c_hashAuthorized party; hashes binding access token or code to the ID token
acr / amrAuthentication context class / methods used
auth_time / max_ageTime of authentication / maximum allowed age
promptnone, login, consent, select_account
UserInfoOIDC endpoint returning claims for an access token
Discovery/.well-known/openid-configuration metadata document
JWKSJSON Web Key Set with the issuer's public keys
Dynamic client registrationRFC 7591 API to register clients
Hybrid flowresponse_type=code id_token and variants
response_mode / form_postHow the authorization response is delivered
RP-initiated logoutRP redirects to end_session_endpoint
Front-channel logoutOP loads RP logout URIs in iframes
Back-channel logoutOP POSTs a logout_token to RPs
SSOOne login at an IdP reused by many applications
SAML 2.0OASIS XML standard for SSO assertions
SP-initiated / IdP-initiatedSSO started at the app / at the IdP portal
FederationTrusting an IdP run by another organisation
Identity brokerIdP in the middle that accepts upstream IdPs and issues its own tokens
Social loginLogin through Google, GitHub, Apple and others
CSRFCross-site request forgery; here on the redirect endpoint
Token leakageTokens exposed via URLs, Referer, logs, storage
BFFBackend-for-frontend holding tokens for a browser app
HttpOnly cookieCookie unreadable by JavaScript
Token-mediating backendBackend keeps refresh token, gives access tokens to JS
PARPushed Authorization Requests, RFC 9126
JARJWT-Secured Authorization Request, RFC 9101
mTLS client authenticationRFC 8705 client certs and certificate-bound tokens
DPoPRFC 9449 proof-of-possession with a signed header per request
Sender-constrained tokenToken usable only with a key or certificate
cnfConfirmation claim (x5t#S256, jkt)
FAPIOpenID Foundation Financial-grade API security profile
Token exchangeRFC 8693 grant to trade one token for another
Delegation / impersonationActor keeps identity (act) / actor becomes the subject
IntrospectionRFC 7662 check of a token at the AS (active)
RevocationRFC 7009 invalidation of a token
invalid_grant / invalid_clientBad code or refresh token / failed client authentication
insufficient_scope / invalid_tokenRS errors 403 / 401
hd / tidGoogle Workspace domain / Entra ID tenant claim
Keycloak, Auth0, Okta, Entra ID, CognitoIdP products
Ory Hydra, DexGo-based OAuth/OIDC servers
Passport / SocialiteLaravel OAuth server / OAuth client
go-oidc / x/oauth2Go OIDC verifier / Go OAuth client library

References ​

Built by Morteza Negahi