Back to docs
Recipe
OAuth flow design
A step-by-step recipe for designing secure, user-friendly OAuth 2.0 authorization flows in your application.
Ingredients
- OAuth 2.0 provider (Google, GitHub, Discord, etc.)
- Client ID and Client Secret
- Redirect URI registered with the provider
- State parameter for CSRF protection
- PKCE code verifier and challenge (for public clients)
Steps
- Generate PKCE pair. Create a cryptographically random code verifier (43–128 chars) and derive its SHA-256 challenge. Store the verifier server-side or in a secure httpOnly cookie.
- Build the authorization URL. Include response_type=code, client_id, redirect_uri, scope, state, and code_challenge with method=S256. Encode all values properly.
- Redirect the user. Send a 302 to the provider's /authorize endpoint. The state parameter binds the request to the user's session.
- Handle the callback. On GET /callback, verify state matches the stored value. Reject if mismatched or missing.
- Exchange the code. POST to the provider's /token endpoint with grant_type=authorization_code, code, redirect_uri, and code_verifier. Parse the access_token and optional refresh_token from the JSON response.
- Fetch user identity. Use the access token to call the provider's userinfo endpoint. Map the returned subject (sub) claim to your internal user record.
- Issue your own session. Create a server-side session (cookie or token). Never expose the provider access token to the browser.
Security notes
- Always validate redirect_uri against an allowlist.
- Use PKCE even for confidential clients — it costs nothing.
- Rotate refresh tokens on each use and detect replay.
- Scope tokens to the minimum required permissions.
- Log all authorization events for audit trails.
Next: Token refresh strategies