SyntaxStudy
Sign Up
REST API OAuth 2.0 Authorization Code Flow
REST API Beginner 1 min read

OAuth 2.0 Authorization Code Flow

OAuth 2.0 is the industry-standard framework for delegated authorization. It lets users grant third-party applications limited access to their data without sharing passwords. The Authorization Code flow is recommended for server-side and native apps: the client redirects the user to the authorization server, which returns a code that the client exchanges for tokens. PKCE (Proof Key for Code Exchange) extends the Authorization Code flow for public clients (SPAs, mobile apps) where a client secret cannot be safely stored. The client generates a code verifier and derives a code challenge from it; the server verifies the challenge when issuing tokens, preventing authorization code interception attacks.
Example
# OAuth 2.0 Authorization Code + PKCE flow

# Step 1: Generate PKCE values (client-side)
# code_verifier = crypto.randomBytes(32).toString('base64url')  // 43-128 chars
# code_challenge = base64url(sha256(code_verifier))

# Step 2: Redirect user to authorization server
GET https://auth.example.com/oauth/authorize?
  response_type=code
  &client_id=my-app
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
  &scope=openid%20profile%20email%20read%3Aposts
  &state=xyz_random_csrf_token
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256

# Step 3: User authorizes → auth server redirects back
# https://app.example.com/callback?code=AUTH_CODE&state=xyz_random_csrf_token

# Step 4: Exchange code for tokens (server-to-server)
POST https://auth.example.com/oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=AUTH_CODE
&redirect_uri=https://app.example.com/callback
&client_id=my-app
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

# Token response
HTTP/1.1 200 OK
{
  "access_token":  "eyJ...",
  "token_type":    "Bearer",
  "expires_in":    3600,
  "refresh_token": "eyJ...",
  "scope":         "openid profile email read:posts",
  "id_token":      "eyJ..."
}