Cybersecurity

OAuth 2.0 Explained for Beginners

RAG Cybersecurity Encryption Authentication OAuth JWT Git GitHub Rust Credentials Passwords Hashing TLS HTTPS
1,541 words Includes Code
Key Takeaway: OAuth 2.0 is an authorization framework — it lets users grant third-party apps limited access to their data without sharing passwords. It involves five roles: Resource Owner, Client, Authorization Server, Resource Server, and (optionally) a Redirect URI.

OAuth 2.0 Explained for Beginners

When you click "Sign in with Google" on a third-party app, OAuth 2.0 is working behind the scenes. It lets the app access your Google profile, photos, or calendar without ever seeing your Google password. This is not just a convenience — it's a fundamental security architecture used by every major platform.

This article explains what OAuth 2.0 actually does, defines each role clearly, walks through the Authorization Code flow step by step, covers the four grant types, and shows you how to use interactive tools to understand tokens and security.

OAuth 2.0 five roles: Resource Owner Client Authorization Server and Resource Server with 5-step Authorization Code flow
OAuth 2.0 involves five roles working together. The Authorization Code flow is the most secure and widely used.

The Core Problem OAuth Solves

Imagine you want a third-party app (say, a photo printing service) to access your Google Photos. Without OAuth, you'd have to give the app your Google password. That's terrible for security:

  • The app now has your full Google access — not just photos
  • If the app is compromised, your Google account is compromised
  • You can't revoke access to just that app without changing your password

OAuth solves this by letting you grant limited, revocable access without sharing your password:

Without OAuth: You give the app your Google password → full access to everything

With OAuth: Google asks "Allow this app to see your photos?" → You say yes → App gets a limited token → You can revoke it anytime

The 5 Roles of OAuth 2.0

Role Who Responsibility
Resource Owner The user (you) Owns the data and grants permission
Client The third-party app Requests access and uses the token to call the API
Authorization Server Google / GitHub / etc. Authenticates the user and issues tokens
Resource Server The API hosting the data Validates tokens and serves protected resources
Redirect URI Configured endpoint Where the auth server sends the user back after consent
⚠️ Important distinction: OAuth 2.0 is for authorization ("can this app access my data?"), not authentication ("who am I?"). For authentication, you need OpenID Connect (OIDC) — a layer built on top of OAuth 2.0.

The Authorization Code Flow

The Authorization Code grant is the most secure and widely used OAuth 2.0 flow. Here's exactly what happens when you click "Sign in with Google":

OAuth 2.0 Authorization Code flow showing 9 steps from user click to API access with code exchange and token
The 9-step Authorization Code flow: the client never sees the user's password. The code is exchanged server-to-server for a token.
Step 1: User clicks "Sign in with Google"
        → Client redirects browser to Google's /authorize endpoint

Step 2: Client sends authorization request:
        GET https://accounts.google.com/o/oauth2/auth?
            client_id=abc123&
            redirect_uri=https://myapp.com/callback&
            response_type=code&
            scope=openid profile email&
            state=RANDOM_CSRF_TOKEN

Step 3: Google shows consent screen:
        "MyApp wants to access your email and profile"

Step 4: User clicks "Allow"

Step 5: Google redirects back with authorization code:
        https://myapp.com/callback?code=AUTH_CODE_xyz789&state=RANDOM_CSRF_TOKEN

Step 6: Client exchanges code for token (server-to-server):
        POST https://oauth2.googleapis.com/token
        Body: code=AUTH_CODE_xyz789&
              client_id=abc123&
              client_secret=SECRET_456&
              redirect_uri=https://myapp.com/callback&
              grant_type=authorization_code

Step 7: Google returns access token (and optionally refresh token):
        {
          "access_token": "eyJhbGciOiJSUzI1NiIs...",
          "token_type": "Bearer",
          "expires_in": 3600,
          "refresh_token": "1//0gABCdefGHI...",
          "scope": "openid profile email"
        }

Step 8: Client uses access token to call API:
        GET https://www.googleapis.com/oauth2/v3/userinfo
        Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

Step 9: Resource Server validates token and returns data:
        {
          "sub": "1234567890",
          "name": "Alice Smith",
          "email": "alice@example.com"
        }

Understanding the Tokens

OAuth 2.0 uses two types of tokens. Understanding the difference is critical:

Property Authorization Code Access Token
Lifespan Seconds (single use) Minutes to hours
Used for Exchanging for access token Calling protected APIs
Transmitted via Query parameter (browser redirect) Authorization header (API calls)
Security Exchanged server-to-server Sent with every API request

Decode tokens: Use the JWT Decoder to see what's inside an access token. Check expiry with the JWT Expiration Checker.

The Four Grant Types

OAuth 2.0 defines several ways to obtain tokens, called "grant types":

Grant Type Use Case Security
Authorization Code Web apps, SPAs with backend, mobile apps (with PKCE) Most secure
Client Credentials Machine-to-machine (no user involved) Secure (server-only)
Resource Owner Password Legacy apps (username + password directly) Deprecated — avoid
Implicit Legacy SPAs (token in URL fragment) Deprecated — use Auth Code + PKCE
For new applications: Use Authorization Code + PKCE for user-facing apps and Client Credentials for server-to-server. Avoid the Resource Owner Password and Implicit grants — they are deprecated in OAuth 2.1.

What is PKCE?

PKCE (Proof Key for Code Exchange, pronounced "pixy") prevents authorization code interception attacks. It's required for public clients (mobile apps, SPAs) and recommended for all applications:

Standard Authorization Code flow:
  Client → Auth Server: "Give me a code"
  Auth Server → Client: "Here's code xyz"
  Client → Auth Server: "Exchange xyz for token"

With PKCE:
  Client generates: code_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r"
  Client computes:  code_challenge = SHA256(code_verifier)

  Client → Auth Server: "Give me a code (challenge: SHA256 result)"
  Auth Server → Client: "Here's code xyz (stores challenge)"
  Client → Auth Server: "Exchange xyz for token (here's the original verifier)"
  Auth Server verifies: SHA256(verifier) === stored_challenge ✓

PKCE ensures that even if an attacker intercepts the authorization code, they can't exchange it for a token without the original verifier.

OAuth 2.0 vs Session Cookies vs JWTs

Property Session Cookies JWTs (standalone) OAuth 2.0
Purpose Server-side sessions Stateless auth tokens Cross-app authorization
Password sharing? Yes (during login) Yes (during login) No — never shared
Third-party access? Not designed for it Not designed for it Primary purpose
Revocable? Yes (server-side) No (until expiry) Yes (token revocation)
Cross-domain? Complicated (CORS) Yes Designed for it

Security Best Practices

✅ OAuth 2.0 Security Checklist:

  • ✓ Always use HTTPS for all OAuth endpoints
  • ✓ Use Authorization Code + PKCE (not Implicit or ROPC)
  • ✓ Validate the state parameter to prevent CSRF
  • ✓ Use exact redirect URI matching (no wildcards)
  • ✓ Never expose client_secret in browser-side code
  • ✓ Set short token expiration (15-60 min for access tokens)
  • ✓ Implement refresh token rotation
  • ✓ Store tokens in httpOnly cookies or secure backend storage
  • ✓ Validate tokens on every API request
  • ✓ Implement token revocation for logout
  • ✓ Use the Security Headers Analyzer on your OAuth endpoints
  • ✓ Set appropriate CORS headers with the CORS Header Generator

Common OAuth Mistakes

❌ Mistake 1: Not Validating the state Parameter

CSRF Attack: An attacker initiates an OAuth flow with their own account, gets your app to link to the attacker's account. Without state validation, you can't detect this.

Fix: Generate a random state, store it in the session, and verify it when the callback arrives.

❌ Mistake 2: Using Implicit Grant

Token Exposure: The Implicit grant puts the access token directly in the URL fragment, making it visible in browser history, referrer headers, and logs.

Fix: Use Authorization Code + PKCE instead. The token is exchanged server-to-server.

❌ Mistake 3: Overly Broad Redirect URIs

Open Redirect: If you allow https://myapp.com/* as a redirect URI, an attacker can redirect the authorization code to https://myapp.com/evil.

Fix: Use exact redirect URI matching. Register https://myapp.com/callback, not https://myapp.com/*.

Real-World OAuth Examples

Action OAuth Provider Scopes Requested
"Sign in with Google" Google openid, profile, email
"Connect with GitHub" GitHub read:user, user:email
Post to Twitter from Buffer Twitter/X tweet.write, users.read
Access Google Drive files Google drive.readonly

Try It Yourself: BestWordz Tools

Token Inspection

Security Headers

Token Generation

OAuth 2.0 in One Sentence

User tells Authorization Server: "I trust this app — give it a limited token."

The app never sees the password. The token is scoped, temporary, and revocable.

Conclusion

OAuth 2.0 is not authentication — it's authorization. It lets users grant third-party apps limited, revocable access to their data without sharing passwords. The Authorization Code flow is the gold standard: the user authenticates directly with the authorization server, receives a short-lived code, and the client exchanges it for a scoped access token.

Understanding the five roles (Resource Owner, Client, Authorization Server, Resource Server, Redirect URI) and the security requirements (state validation, PKCE, exact redirect matching) is essential for every developer building login systems or third-party integrations.

Related BestWordz Resources

Explore all BestWordz Cybersecurity Tools →

💬 Discuss on BestWordz Community

Join the conversation about RAG, Cybersecurity, Encryption on the BestWordz Community forum.

Visit Forum →