OAuth 2.0 is an authorization framework, not a shortcut for collecting a user's provider password. A web application should redirect the user to the identity or authorization provider, receive a short-lived authorization code and exchange it through the back channel. For public clients and modern deployments, Proof Key for Code Exchange (PKCE) protects the authorization code against interception.
Start an authorization transaction
Generate a cryptographically random state value and bind it to the user's session. Generate a high-entropy code_verifier, derive its SHA-256 code_challenge, and send the challenge using the S256 method. Use an exact, pre-registered redirect URI. Do not accept arbitrary callback URLs from query parameters. Store the verifier and transaction metadata server-side with a short expiry.
Validate the callback
When the provider redirects back, compare the returned state with the session-bound value using a timing-safe comparison. Reject missing, expired or mismatched state. Exchange the code at the provider's token endpoint using the original redirect URI and code verifier. Validate the token response and follow the provider's documented issuer, audience and signature rules when receiving identity tokens; an access token is not automatically proof of user identity.
Protect tokens
Keep client secrets and refresh tokens on the server, encrypted or otherwise protected at rest according to the threat model. Do not place them in browser local storage or URLs. Request the minimum scopes needed. Rotate refresh tokens when the provider supports rotation, handle revocation and define what happens when consent is withdrawn.
Avoid common mistakes
Do not use the implicit grant for a new application. Do not skip state validation, reuse a code verifier, accept wildcard redirect URIs or treat an unverified email claim as a trusted account link. Use OpenID Connect when the application needs a standardized authentication layer on top of OAuth 2.0.
Further reading
- RFC 6749: OAuth 2.0 — https://www.rfc-editor.org/rfc/rfc6749
- RFC 7636: PKCE — https://www.rfc-editor.org/rfc/rfc7636
- OpenID Connect — https://openid.net/developers/how-connect-works/