Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API Security APIs APIs From Zero to Real-World API Testing & Automation Authentication Module 5 — API Authentication OAuth

OAuth 2.0 Explained for Beginners — Flows, Tokens, and Use Cases

Reviewed & accurate
AI Summary

What You'll Learn

  • What OAuth 2.0 is and what problem it solves
  • The four main OAuth flows and when to use each
  • How scopes limit what an app can do
  • How refresh tokens extend sessions safely

Why This Matters

OAuth 2.0 is the protocol behind "Log in with Google", "Log in with GitHub", and most modern API authentication. If you build apps that access user data on other services, you will use OAuth. If you build an API that third-party apps want to access, you will implement OAuth. There is no way around it.

The Problem OAuth Solves

Before OAuth, if you wanted an app to read your Gmail, you gave the app your Gmail password. The app then had full access to your account — it could read mail, send mail, change your password, delete everything. You had no way to limit it. And if the app was hacked, your password was leaked.

OAuth fixes this by introducing a layer between the user and the app:

  • The user authenticates directly with the service (Google).
  • The service issues a token to the app with limited permissions (scopes).
  • The app uses the token — never sees the password.
  • The user can revoke the token at any time without changing their password.

Real-World Analogy — Valet Parking

When you use valet parking, you don't give the valet your house key and your car key and your wallet. You give them a valet key that starts the car but cannot open the trunk or glove compartment. OAuth works the same way: instead of giving an app your password, you give it a limited token that can do only specific things.

The Key Concepts

Resource Owner

The user who owns the data. (You, when an app wants to access your GitHub repos.)

Client

The app that wants to access the data. (A third-party tool that wants to read your GitHub repos.)

Authorization Server

The server that authenticates the user and issues tokens. (GitHub's auth server.)

Resource Server

The server that holds the data the client wants. (GitHub's API server.)

Scopes

Permissions the token grants. Examples: read:user, repo, write:org. Scopes limit what the client can do.

Access Token

The credential the client uses to access the API. Short-lived (often 1 hour).

Refresh Token

A longer-lived token used to get new access tokens without asking the user to log in again. Revocable.

The Four Main OAuth Flows

1. Authorization Code Flow (most common)

Used by web apps with a backend. The user logs in via a browser, the app receives an authorization code, and the backend exchanges it for tokens.

1. User clicks "Login with Google"
2. Browser redirects to:
   https://accounts.google.com/oauth2/auth?
     response_type=code&
     client_id=YOUR_CLIENT_ID&
     redirect_uri=https://app.example.com/callback&
     scope=read:user email&
     state=random_string

3. User logs in and approves the request

4. Google redirects to:
   https://app.example.com/callback?code=AUTH_CODE&state=random_string

5. App's backend sends:
   POST https://oauth2.googleapis.com/token
   {
     "grant_type": "authorization_code",
     "code": "AUTH_CODE",
     "client_id": "YOUR_CLIENT_ID",
     "client_secret": "YOUR_CLIENT_SECRET",
     "redirect_uri": "https://app.example.com/callback"
   }

6. Google responds:
   {
     "access_token": "ya29...",
     "refresh_token": "1//...",
     "expires_in": 3600,
     "token_type": "Bearer"
   }

The state parameter prevents CSRF attacks. Always include a random value and verify it in the callback.

2. Client Credentials Flow

Used for server-to-server communication. No user involved — the client is the app itself.

POST https://oauth.example.com/token
{
  "grant_type": "client_credentials",
  "client_id": "YOUR_CLIENT_ID",
  "client_secret": "YOUR_CLIENT_SECRET",
  "scope": "read:metrics"
}

Response:
{
  "access_token": "eyJhbGci...",
  "expires_in": 3600,
  "token_type": "Bearer"
}

No refresh token — the client just re-authenticates when the access token expires.

3. Refresh Token Flow

Used to get a new access token without re-prompting the user.

POST https://oauth.example.com/token
{
  "grant_type": "refresh_token",
  "refresh_token": "1//abc...",
  "client_id": "YOUR_CLIENT_ID",
  "client_secret": "YOUR_CLIENT_SECRET"
}

Response:
{
  "access_token": "eyJhbGci...",
  "expires_in": 3600,
  "token_type": "Bearer"
}

4. Implicit Flow (deprecated)

Used by JavaScript-only apps without a backend. The token was returned directly in the URL fragment. Deprecated in favor of Authorization Code Flow with PKCE (Proof Key for Code Exchange) for SPAs.

PKCE — For Mobile and SPA Apps

Apps without a backend (mobile apps, single-page apps) cannot safely store a client secret. PKCE replaces the secret with a dynamically-generated challenge. The flow is the same as Authorization Code, but the client proves it started the request by matching the challenge.

Scopes — Limiting Access

Scopes are how OAuth limits what a token can do. Examples from GitHub:

ScopeAllows
read:userRead user profile
user:emailRead user email
repoFull access to public and private repos
public_repoAccess to public repos only
delete_repoDelete repositories

When the user logs in, they see the scopes the app is requesting and can approve or deny. This is the "valet key" mechanism — the app gets only what it asked for, not full account access.

Common Mistakes

  1. Storing client secrets in frontend code. Frontend code is public. Use Authorization Code Flow with PKCE for SPAs and mobile apps.
  2. Skipping the state parameter. Without it, your flow is vulnerable to CSRF attacks.
  3. Requesting too many scopes. Users will reject the login. Ask for the minimum needed.
  4. Not validating the redirect URI. The redirect URI must exactly match what's registered. Loose matching allows redirect attacks.
  5. Treating refresh tokens as permanent. They can be revoked. Always handle 401 by re-authenticating.
  6. Using Implicit Flow. It's deprecated. Use Authorization Code with PKCE instead.

Practical Exercise (15 minutes)

  1. Go to a service you use (GitHub, Google, Slack) and find its OAuth settings.
  2. Look at the list of apps you've authorized. Each one shows the scopes you granted.
  3. Revoke access for an app you no longer use. Notice how the user remains in control.
  4. Read the docs for any OAuth 2.0 API. Identify: the authorization endpoint, the token endpoint, the available scopes, and the supported flows.

Mini Challenge

Design an OAuth 2.0 integration for a "GitHub analytics" app that needs to read your public repos and show contribution graphs. Write down: (1) which flow will you use? (2) what scopes do you need? (3) where will you store the access token? (4) what happens when the token expires? (5) how does the user revoke access?

Key Takeaways

  • OAuth 2.0 lets users grant apps limited access without sharing passwords.
  • Four main flows: Authorization Code (web apps), Client Credentials (server-to-server), Refresh Token (renew access), Implicit (deprecated).
  • Use PKCE for SPAs and mobile apps that cannot keep a client secret.
  • Scopes limit what a token can do. Request the minimum.
  • Always include the state parameter. Always validate the redirect URI exactly.
Course continuity
Previously: Lesson 29 covered JWT — the token format.
Today: You learned OAuth 2.0 — the protocol that issues those tokens.
Next: Lesson 31 covers token expiration, scopes, and refresh tokens in detail.

FAQ

Is OAuth 2.0 the same as OpenID Connect?

No. OAuth 2.0 is for authorization (what can the app do?). OpenID Connect (OIDC) is built on top of OAuth 2.0 and adds authentication (who is the user?). When you see "Log in with Google", you're using OIDC, not just OAuth.

What is PKCE?

Proof Key for Code Exchange. It replaces the client secret with a dynamically generated challenge. Used by mobile apps and SPAs that cannot safely store a secret. The client sends a code verifier; the auth server hashes it and compares. Without the original verifier, an intercepted authorization code is useless.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments