OAuth 2.0 Explained for Beginners
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.
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 |
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":
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 |
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
stateparameter 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" | 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 | drive.readonly |
Try It Yourself: BestWordz Tools
Token Inspection
- JWT Decoder — Decode any JWT access token
- JWT Claims Viewer — See all claims in a token
- JWT Expiration Checker — Check if a token is expired
- JWT Structure Analyzer — Full structural analysis
- JWT Timestamp Converter — Convert iat/exp timestamps
Security Headers
- Security Headers Analyzer — Check your OAuth endpoint security
- CORS Header Generator — Configure cross-origin for OAuth callbacks
- HSTS Header Generator — Enforce HTTPS on auth endpoints
- Cookie Security Analyzer — Verify token cookie settings
- Secure Cookie Generator — Generate secure session cookies
Token Generation
- Secure Random Token Generator — Generate state and PKCE parameters
- HMAC-SHA256 Generator — Compute code challenges for PKCE
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
- JWT Explained: Header, Payload and Signature — How access tokens work
- Hashing vs Encryption vs Encoding — The crypto behind OAuth tokens
- How HTTPS and TLS Actually Work — TLS protects OAuth in transit
- Protecting API Keys and Secrets — Why client_secret must stay server-side
- Hashing vs Encryption vs Encoding Demo — Interactive comparison
💬 Discuss this topic
Have questions or insights about OAuth 2.0 Explained for Beginners? Join the BestWordz Community.
📚 Related Articles
API Authentication Methods Compared
Key Takeaway --> There is no single "best" API authentication method. API keys are simple but weak…
CybersecuritySecrets Management for Developers: From .env Files to Secret Managers
KEY TAKEAWAY Secrets management is the practice of storing, accessing, rotating and revoking cred…
CybersecurityHashing vs Encryption vs Encoding: What's the Difference?
Key Takeaway --> Hashing verifies integrity and stores passwords safely. Encryption keeps data con…
CybersecuritySQL Injection Explained and Prevented
KEY TAKEAWAY SQL injection occurs when user input is concatenated directly into a SQL query strin…
CybersecurityJWT Explained: Header, Payload and Signature
Key Takeaway --> A JWT is three Base64URL-encoded parts separated by dots: header (algorithm), pay…
CybersecurityCross-Site Scripting Explained for Web Developers
KEY TAKEAWAY Cross-Site Scripting (XSS) happens when untrusted user input is included in web page…
🔧 Related Tools
CORS Header Generator
Generate CORS headers.
Try it now →Hashing vs Encryption vs Encoding Demo
Understand the fundamental difference between hashing, encryption, and encoding.
Try it now →HMAC-SHA256 Generator
Generate an HMAC-SHA256 signature from a key and message, entirely in your browser.
Try it now →JWT Claims Viewer
View and analyze JWT claims with explanations and security warnings.
Try it now →💬 Discuss on BestWordz Community
Join the conversation about RAG, Cybersecurity, Encryption on the BestWordz Community forum.
Visit Forum →