OAuth 2.0 Authorization Code Flow Explained
A complete walkthrough of the OAuth 2.0 Authorization Code grant type. Learn how the client, authorization server, and resource server interact step by step.
Detailed Explanation
The Authorization Code Flow
The Authorization Code flow is the most widely used OAuth 2.0 grant type and the foundation for secure authentication in web applications with a backend server. It involves a front-channel redirect (browser) and a back-channel token exchange (server-to-server), which keeps the access token away from the user's browser.
How It Works
Authorization Request: The client redirects the user's browser to the authorization server's
/authorizeendpoint withresponse_type=code,client_id,redirect_uri,scope, and a randomstateparameter.User Authentication: The authorization server presents a login page and consent screen. The user authenticates and grants permission.
Authorization Code: The authorization server redirects back to the client's
redirect_uriwith a short-livedcodeparameter and the originalstate.Token Exchange: The client's backend server sends a POST request to the
/tokenendpoint with the authorization code,client_id,client_secret, andredirect_uri.Access Token: The authorization server validates everything and returns an access token (and optionally a refresh token).
API Access: The client includes the access token in the
Authorization: Bearerheader when calling the resource server's API.
Why Use a Code Instead of a Token Directly?
The authorization code acts as an intermediary. Because the token exchange happens on the back channel (server-to-server), the access token is never exposed to the user's browser, browser history, or referrer headers. The state parameter prevents CSRF attacks by ensuring the callback came from a request the client initiated.
Security Considerations
- Always validate
stateon the callback - Use HTTPS for all endpoints
- Authorization codes must be single-use and short-lived (typically 10 minutes)
- Store
client_secretsecurely on the server, never in client-side code
Use Case
A traditional web application (e.g., a Node.js/Express or Django backend) that needs to authenticate users via Google, GitHub, or any OAuth 2.0 provider. The server stores the client_secret securely and handles the token exchange behind the scenes.