How OAuth 2.0 authorization code flow works
OAuth 2.0 roles, authorization server, resource server, client, authorization code, access token, redirect URI, state parameter, PKCE
Four Roles, One Flow
OAuth 2.0 lets users grant your app access to their data on another service without giving you their password. The four roles are: Resource Owner (the user), Client (your app), Authorization Server (Google's login server), and Resource Server (Google's API).
The Authorization Code Flow
- User clicks "Login with Google" on your app
- Your app redirects to Google's authorization URL with your client_id, scope, redirect_uri, and a random state value
- User logs in to Google and grants permission
- Google redirects back to your redirect_uri with an authorization code and the state value
- Your server exchanges the code for an access token via a server-to-server POST request
- You use the access token to fetch the user's profile from Google's API
The State Parameter
The state value you generate in step 2 must be validated when it comes back in step 4. This prevents CSRF attacks on the OAuth callback โ an attacker cannot forge a callback without knowing your randomly generated state. Store it in the session before the redirect; compare it on callback.
PKCE
PKCE (Proof Key for Code Exchange) adds protection against authorization code interception in public clients (mobile apps, SPAs). It is now recommended for all OAuth flows, including server-side apps.
