Skip to main content

πŸ” OAuth 2.0 Flows

OAuth (Open Authorization) is an open standard that allows applications to access resources on behalf of a user without requiring their password.

Example: When you log in to a new website using β€œLogin with Google,” you don’t give your Google password to that website. Instead, Google gives a temporary access token that allows limited access to your information.


🧩 Core Components​

RoleDescriptionExample
Resource OwnerThe user who owns the dataYou
ClientThe app that wants accessSpotify
Authorization ServerIssues tokens after user consentGoogle OAuth
Resource ServerHosts the protected dataGoogle APIs

🧠 Why Multiple OAuth 2.0 Flows Exist​

Different app types have different security levels and capabilities.

  • Web servers can store secrets safely.
  • Mobile / SPA apps cannot.
  • Machine-to-machine systems have no user at all.

Hence, OAuth 2.0 defines different flows for different use cases.


πŸš€ OAuth 2.0 Flows

1️⃣ Authorization Code Flow (For Server-side Web Apps)​

Used by apps with a secure backend that can store a client secret.

πŸ”„ Steps​

  1. User clicks β€œLogin with Google.”
  2. App redirects the user to Google’s OAuth endpoint.
  3. User logs in and approves permissions.
  4. Google redirects back with an authorization code.
  5. Backend exchanges that code (using clientid) for an access token and optional refresh token.
  6. Further Backend communicate securily using access_token

βœ… Pros​

  • Very secure (tokens never exposed to the browser).
  • Can get refresh tokens for long sessions.

❌ Cons​

  • Requires a backend server.
  • Server should use HTTPS for security

2️⃣ Authorization Code Flow with PKCE (For Mobile & SPAs)​

PKCE = Proof Key for Code Exchange

Used when the app cannot store a client_secret, e.g. mobile apps or SPA.

πŸ”’ How It Works​

  1. App generates a random code_verifier and a code_challenge (hash of it).
    1. code_verifier = SHA256(code_challenge)
  2. Sends code_challenge with the auth request.
  3. After login, receives the authorization code.
  4. Exchanges the code + original code_verifier for tokens.
  5. Auth Server validates the hash to ensure it’s the same app that initiated login.

βœ… Pros​

  • Secure even for public clients (no secret needed).
  • Prevents authorization code interception attacks.
  • No XSS attack possible as code_verifier is generated and stored in frontend app state not in local storage or something.

❌ Cons​

  • Slightly more complex setup.

3️⃣ Implicit Flow (Deprecated)​

Used by SPAs before PKCE existed. Tokens were returned directly in the redirect URL.

⚠️ Why Not to Use​

Tokens in URLs can be exposed to browser history, extensions, or logs. Now replaced by PKCE flow.


4️⃣ Client Credentials Flow (Machine-to-Machine)​

Used when no user is involved β€” just two backend services communicating.

βœ… Pros​

  • Simple and efficient for service-to-service communication.

❌ Cons​

  • Represents the application only, not a user.
  • Must secure the client_secret.

5️⃣ Resource Owner Password Credentials (ROPC) Flow (Legacy)​

User provides their username and password directly to the app.

Breaks OAuth’s purpose β€” the app could steal the password. Use only for trusted internal systems (and even then, avoid it).


6️⃣ Device Code Flow (For TVs / IoT Devices)​

Used when device has no browser or keyboard.

πŸ”„ How It Works​

  1. Device shows a code and asks user to visit a URL (e.g., google.com/device).
  2. User logs in from another device and enters the code.
  3. Device polls the server until approved, then receives a token.

βœ… Pros​

  • Works on limited-input devices.

❌ Cons​

  • Slower, more complex UX.

πŸ” PKCE β€” Deep Dive

PKCE (Proof Key for Code Exchange) prevents attackers from stealing the authorization code.

StepTermDescription
1code_verifierRandom string kept secret in the app
2code_challengeSHA256 hash of verifier sent to auth server
3authorization_codeReceived after user login
4code_verifier againSent later to prove it’s the same app

βœ… This ensures even if someone steals the authorization code, they can’t exchange it for tokens without the code_verifier.


🧰 Security Concepts to Know

ConceptDescription
Access TokenUsed to access protected resources (short-lived)
Refresh TokenUsed to get new access tokens without login
Client SecretPrivate credential for confidential clients
ScopeDefines what access is granted (e.g., email, profile)
Redirect URICallback URL after user authorization
State ParameterRandom string to prevent CSRF attacks
  • state param is used like, when client redirect to auth provider it adds a random generate state in query param and store it locally. so when auth server redirect back to client it verifies that state should be present and same. The issue it solves is even if attacker tricks user to visit malicious link on redirect back client will know it is a csrf issue as token will be wrong or not present.

βš”οΈ Common Attacks & Mitigations

AttackDescriptionPrevention
Authorization Code InterceptionAttacker steals code from redirectUse PKCE
Token ReplayReuse of old tokenShort-lived tokens, use HTTPS
CSRF (Cross-site request forgery)Fake redirect or callbackUse state param
Token Leakage in URLsTokens in fragment or queryAvoid Implicit Flow
Refresh Token AbuseCompromised long-term tokenUse rotation and revocation

πŸ†š OAuth 1.0 vs OAuth 2.0

FeatureOAuth 1.0OAuth 2.0
Signing methodCryptographic signaturesBearer tokens (simpler)
Ease of implementationComplexEasier, but requires HTTPS
Token typeRequest/Access tokensAccess/Refresh tokens
Mobile/SPA supportPoorExcellent (via PKCE)
ExtensibilityLimitedHighly extensible
SecurityBuilt-in signingRelies on HTTPS + PKCE
Use today?DeprecatedStandard

OAuth 2.0 simplified the protocol but shifted more responsibility to developers for security.


πŸ“š Extra Things You Should Know

  • OIDC (OpenID Connect): Layer built on OAuth 2.0 for authentication (identity), adds id_token (JWT).
  • JWT (JSON Web Token): Common token format β€” signed, optionally encrypted, self-contained.
  • Token Introspection: Endpoint to verify token validity.
  • Token Revocation: Endpoint to revoke access or refresh tokens.
  • Scopes & Consent UI: Always request minimum scopes necessary for principle of least privilege.
  • Use HTTPS always: OAuth 2.0 assumes all communication is encrypted.
  • Avoid storing tokens in localStorage in SPAs β€” use memory or HTTP-only cookies instead.

🧭 Quick Decision Table

Use CaseRecommended Flow
Web App (Backend)Authorization Code Flow
SPA / Mobile AppAuthorization Code + PKCE
Service ↔ ServiceClient Credentials
Smart TV / IoTDevice Code Flow
Legacy SystemAvoid, but ROPC if unavoidable