Drafting sections for diagrams
I’m planning to offer sections with bullet lists and small diagrams. I’ll start by drafting sequence diagrams in Mermaid format for Authorization Code with PKCE, Client Credentials, Refresh, and Logout. I must remember to include disclaimers about needing to validate the ID token. Once I have everything organized, I’ll produce the final answer in Markdown format to ensure it’s both clear and easy to read. Let's get started!
1) OAuth 2.1 vs OIDC (what each is)
OAuth 2.1 (draft at time of writing, but widely implemented behavior) is an authorization framework: it lets a client obtain an access token to call an API (resource server) on behalf of a user (resource owner) or as itself.
OpenID Connect (OIDC) is an identity layer on top of OAuth: it standardizes authentication and user identity via an ID token and optional UserInfo endpoint.
Key OAuth 2.1 “direction”
OAuth 2.1 effectively standardizes modern best practice:
- Authorization Code is the primary user-based flow.
- PKCE is required for public clients (and recommended for all).
- Implicit flow is removed.
- Resource Owner Password Credentials (ROPC) is discouraged/removed.
- Strong redirect URI validation, state, etc.
2) Roles and endpoints (terminology)
- Authorization Server (AS): issues tokens (often also an OIDC Provider).
- Client: your app (web app, SPA, mobile, backend).
- Resource Server (RS): API receiving access tokens.
- User / Resource Owner: the human.
- Relying Party (RP): OIDC term for the client relying on identity.
Common endpoints:
/.well-known/openid-configuration (OIDC discovery)
/authorize (front-channel authorization request)
/token (back-channel token exchange)
/jwks (public signing keys)
/userinfo (OIDC user claims)
/revocation (token revocation, RFC 7009)
/introspect (token introspection, RFC 7662; mainly for opaque tokens)
/logout (OIDC RP-initiated logout; vendor-specific variations)
3) Core flows
A) Authorization Code Flow + PKCE (recommended for web, SPA, mobile)
This is the modern default for “sign in and call APIs”.
Sequence diagram
sequenceDiagram
autonumber
participant U as User (Browser)
participant C as Client (SPA/Web/Mobile)
participant AS as Authorization Server (OIDC Provider)
participant RS as API (Resource Server)
C->>C: Generate code_verifier + code_challenge (PKCE)
C->>U: Redirect to /authorize (response_type=code, code_challenge, state, nonce)
U->>AS: GET /authorize ... (user authenticates, consents)
AS->>U: Redirect back to redirect_uri?code=...&state=...
U->>C: Deliver code
C->>AS: POST /token (grant_type=authorization_code, code, code_verifier, redirect_uri)
AS-->>C: access_token (+ id_token if OIDC) (+ refresh_token if allowed)
C->>RS: Call API with Authorization: Bearer access_token
RS-->>C: Protected data
Why PKCE matters: it prevents an attacker who steals the authorization code from redeeming it without the original code_verifier.
B) Client Credentials (machine-to-machine)
Used when no user is involved (service calls API as itself).
sequenceDiagram
autonumber
participant S as Service (Client)
participant AS as Authorization Server
participant RS as API
S->>AS: POST /token (grant_type=client_credentials, client_id, client_secret or mTLS)
AS-->>S: access_token
S->>RS: Authorization: Bearer access_token
RS-->>S: Protected resource
No OIDC ID token here (OIDC is about users).
C) Device Authorization Grant (TVs, CLI devices)
User completes login on a secondary device. (Often recommended for CLIs.)
4) Tokens (what they are and how to validate)
Access token (OAuth)
- Presented to APIs:
Authorization: Bearer <token>
- Usually short-lived (minutes)
- Can be:
- JWT (self-contained, signed)
- Opaque (random string; RS uses introspection or AS-side session)
If JWT access token, the API validates:
- Signature (via AS JWKS)
iss (issuer)
aud (audience = API identifier)
exp, nbf
- Scopes/roles claims (implementation-specific)
- Optional
azp, client_id, sub, jti
Refresh token (OAuth)
- Used by the client to get new access tokens without user interaction.
- Should be protected like a password.
- Often long-lived but should use rotation (best practice).
ID token (OIDC)
- A JWT asserting user authentication.
- Audience is the client (not the API).
- Contains identity claims:
sub, and possibly email, name, etc.
- Must validate: signature,
iss, aud, exp, and nonce (for browser-based flows).
Common ID token claims:
iss, sub, aud, exp, iat
nonce (binds to auth request)
auth_time, acr (auth strength), amr (methods)
at_hash (ties ID token to access token in some flows)
5) Scopes vs Claims (and how OIDC uses them)
OAuth scopes (authorization)
Scopes are permissions the client requests. Example:
read:invoices, write:invoices
The access token (or introspection response) conveys granted scopes to the API.
OIDC scopes (identity)
OIDC defines standard scopes:
openid (required to get an ID token)
profile, email, address, phone
offline_access (request refresh token; AS policy dependent)
Claims (attributes about the user/client)
Claims can appear in:
- ID token (identity/authentication)
- UserInfo response
- Sometimes access tokens (authorization context)
Example: requesting OIDC scopes:
scope=openid profile email → may yield claims like name, preferred_username, email.
6) PKCE (how it works + snippet)
PKCE parameters
code_verifier: random high-entropy string (43–128 chars)
code_challenge = BASE64URL(SHA256(code_verifier))
code_challenge_method=S256
JS snippet: generate PKCE pair
// Browser or Node (with WebCrypto)
function base64url(bytes) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function pkcePair() {
const verifierBytes = crypto.getRandomValues(new Uint8Array(32));
const verifier = base64url(verifierBytes);
const hash = new Uint8Array(await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(verifier)
));
const challenge = base64url(hash);
return { verifier, challenge, method: "S256" };
}
7) Refresh tokens (rotation, SPAs, and “offline_access”)
Refresh flow diagram
sequenceDiagram
autonumber
participant C as Client
participant AS as Authorization Server
participant RS as API
C->>AS: POST /token (grant_type=refresh_token, refresh_token=RT1)
AS-->>C: access_token=AT2, refresh_token=RT2 (rotation)
C->>RS: Bearer AT2
RS-->>C: OK
Note over AS,C: If RT1 is reused, AS can detect theft and revoke the chain.
Best practices
- Refresh Token Rotation + reuse detection.
- Keep access tokens short-lived.
- Limit refresh token lifetime; use sliding windows if needed.
- Use
offline_access only when the client truly needs long-lived sessions.
SPAs: refresh tokens in the browser are risky. Prefer:
- BFF pattern (Backend-for-Frontend): tokens stored server-side; browser gets a session cookie.
- If you must use SPA refresh tokens, use AS features like rotation + sender-constrained tokens (DPoP) and store tokens carefully (see browser security below).
8) Browser security essentials (redirects, CSRF, token storage, CORS)
Must-have parameters
state: CSRF protection for the authorization response. Verify it exactly.
nonce (OIDC): binds ID token to the auth request; verify it.
Redirect URI rules
- Register exact redirect URIs.
- Avoid wildcards if possible.
- Use HTTPS except loopback for native apps (per best current practices).
Token storage in browsers
- Avoid storing tokens in
localStorage (XSS can exfiltrate).
- Prefer:
- BFF: store tokens on server; browser has HttpOnly + Secure + SameSite cookie session.
- If pure SPA: keep access token in memory, use short lifetime, consider DPoP, strict CSP, and rotation.
CSRF and cookies
If you use cookies to your backend:
- Use SameSite=Lax/Strict where possible.
- If cross-site is necessary (e.g., different domains), use
SameSite=None; Secure and add CSRF tokens.
CORS
CORS protects the browser, not your API. Your API must still validate tokens. Keep CORS allowlists tight.
Clickjacking and mixups
- Use
frame-ancestors CSP / X-Frame-Options.
- Ensure the client can’t be tricked into accepting tokens from the wrong issuer (validate
iss, use discovery carefully).
9) Logout (OIDC logout patterns)
Logout is not “built into” OAuth; OIDC standardizes several approaches.
A) RP-Initiated Logout (front-channel)
Client redirects user to provider logout endpoint, often with:
id_token_hint (which session to end)
post_logout_redirect_uri
state
sequenceDiagram
autonumber
participant U as User (Browser)
participant C as Client
participant AS as OIDC Provider
C->>U: Redirect to AS /logout?id_token_hint=...&post_logout_redirect_uri=...
U->>AS: GET /logout ...
AS->>U: Clears AS session cookies
AS-->>U: Redirect back to post_logout_redirect_uri
U->>C: Arrives logged out (client clears its session)
B) Back-channel logout
AS notifies clients server-to-server that a session ended. More reliable for multi-app SSO, but requires backend.
Important caveat
Logging out does not automatically revoke access tokens already issued. If you need that, use:
- token revocation endpoint (
/revocation)
- short access token lifetimes
- session-aware APIs (or introspection)
10) Practical code snippets
A) Build an authorization URL (OIDC, code + PKCE)
GET https://as.example.com/authorize?
client_id=client123&
response_type=code&
redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&
scope=openid%20profile%20email%20api.read&
state=RANDOM_STATE&
nonce=RANDOM_NONCE&
code_challenge=PKCE_CHALLENGE&
code_challenge_method=S256
B) Exchange code for tokens (Node.js)
const params = new URLSearchParams({
grant_type: "authorization_code",
client_id: process.env.CLIENT_ID,
code: authCode,
redirect_uri: "https://app.example.com/callback",
code_verifier: pkceVerifier
});
const res = await fetch("https://as.example.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params
});
const tokenResponse = await res.json();
// tokenResponse: { access_token, id_token, refresh_token?, expires_in, token_type }
C) Verify an ID token (high-level steps)
Use a well-vetted library (do not hand-roll JWT validation). Conceptually:
- Fetch OIDC discovery metadata
- Fetch JWKS
- Verify JWT signature and claims:
iss equals expected issuer
aud contains your client_id
exp not expired
nonce matches what you sent
(Example libraries: jose in Node, Microsoft.IdentityModel.* in .NET, oauth2-client/google-auth in Java, etc.)
D) Refresh token request
curl -X POST https://as.example.com/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "client_id=client123" \
-d "refresh_token=REFRESH_TOKEN_VALUE"
11) Best practices checklist (OAuth 2.1 + OIDC)
Flow choices
- Use Authorization Code + PKCE for user sign-in (web, SPA, mobile).
- Use Client Credentials for service-to-service.
- Use Device Code for CLI/TV where needed.
- Avoid Implicit and ROPC.
Client security
- Public clients: no client secret; rely on PKCE + redirect URI constraints.
- Confidential clients: protect secrets; rotate them; consider mTLS.
Token hygiene
- Short-lived access tokens.
- Refresh token rotation + reuse detection.
- Use the revocation endpoint when a user logs out or disconnects.
- Prefer sender-constrained tokens (DPoP or mTLS) if threat model warrants it.
Validation
- APIs validate: signature,
iss, aud, exp, and authorization (scopes/roles).
- OIDC clients validate ID token + nonce; use discovery carefully and pin issuer.
Browser hardening
- Prefer BFF for SPAs handling sensitive scopes.
- Strong CSP, avoid XSS sinks, no tokens in localStorage.
- Use
state and strict redirect URI matching.
- Use SameSite cookies + CSRF defense when cookies are involved.
Authorization modeling
- Use scopes for coarse permissions, and domain authorization checks in the API.
- Avoid putting overly sensitive data in tokens; tokens are bearer artifacts.
If you tell me your client type (SPA vs server-rendered web vs mobile vs CLI) and whether you control the API, I can recommend a concrete “golden path” architecture (BFF vs pure SPA), token lifetimes, and exact parameters for your provider.