Security & Authentication

OAuth 2.0 Flows Explained: Authorization Code, Client Credentials, PKCE

A practical guide to OAuth 2.0 — when to use each grant type, how the flows work, and security considerations for web apps, SPAs, and machine-to-machine auth.

What Is OAuth 2.0?

OAuth 2.0 is an authorization framework that lets a third-party application access a user's resources without knowing their password. Instead of sharing credentials, the user grants the application a scoped, time-limited access token.

Key Concepts

  • Resource Owner — The user who owns the data
  • Client — The application requesting access
  • Authorization Server — Issues access tokens (e.g., Google, GitHub)
  • Resource Server — The API that accepts access tokens
  • Scope — What the token is allowed to do (e.g., read:email)

Authorization Code Flow

The most common and most secure flow. Used by server-side web applications.

1. App redirects user to authorization server
   → /authorize?response_type=code&client_id=X&redirect_uri=Y&scope=Z

2. User logs in and grants permission

3. Authorization server redirects back with a code
   → /callback?code=AUTH_CODE

4. App exchanges code for tokens (server-to-server)
   → POST /token {grant_type=authorization_code, code=AUTH_CODE, client_secret=S}

5. Authorization server returns access_token + refresh_token

Security: The client_secret never touches the browser. The authorization code is single-use and short-lived.

Authorization Code + PKCE

PKCE (Proof Key for Code Exchange) is required for SPAs and mobile apps that cannot securely store a client secret.

Instead of a client secret, the app generates a random code_verifier and sends its hash (code_challenge) with the authorization request. When exchanging the code, it sends the original code_verifier. The server verifies the hash matches.

code_verifier = random_string(43-128 chars)
code_challenge = BASE64URL(SHA256(code_verifier))

This prevents authorization code interception attacks.

Client Credentials Flow

For machine-to-machine authentication (no user involved).

POST /token
grant_type=client_credentials
client_id=X
client_secret=S
scope=api:read

Returns an access token directly. No user consent needed.

Use for: Background services, cron jobs, microservice-to-microservice auth.

Which Flow to Use?

Client TypeFlow
Server-side web appAuthorization Code
SPA (React, Vue)Authorization Code + PKCE
Mobile appAuthorization Code + PKCE
Backend serviceClient Credentials
IoT deviceDevice Authorization Flow

Common Mistakes

  • Using Implicit Flow — Deprecated. Use Auth Code + PKCE instead.
  • Not validating the state parameter — Opens CSRF attacks.
  • Long-lived access tokens — Use short-lived tokens with refresh tokens.
  • Storing tokens in localStorage — Use HttpOnly cookies or in-memory storage.

相关协议

相关术语表条目

更多内容: Security & Authentication