Overview
Security is paramount when implementing OAuth 2.0. This guide covers essential security practices, common vulnerabilities, and how to protect your application and users from attacks.User Consent and Authorization Principles
OAuth 2.0 is fundamentally about user empowerment and consent. Security extends beyond protecting tokens—it includes respecting the authorization boundaries users establish.User Agency First
Users grant your application permission to act on their behalf. This authorization is not blanket access—it’s permission to perform specific, expected actions.
Principle of Least Privilege
Only request and use the minimum permissions necessary. Just because you have a token doesn’t mean you should access all available user data.
Transparent Intent
Users should always understand what actions your application will perform on their behalf. Unexpected behavior erodes trust and violates consent.
Revocation Rights
Users must be able to revoke access at any time. Implement clear logout flows and honor token revocation immediately.
PKCE Implementation
PKCE (Proof Key for Code Exchange, pronounced “pixie”) is mandatory for all OAuth flows. It prevents authorization code interception attacks.What is PKCE?
PKCE adds a cryptographic challenge to the OAuth flow:- Code Verifier: Random 43-128 character string
- Code Challenge: SHA256 hash of the code verifier
- Verification: Server validates verifier matches challenge
Implementation
PKCE Requirements
Code Verifier
- Length: 43-128 characters
- Character set: [A-Z, a-z, 0-9, -, ., _, ~]
- Cryptographically random
- Single use only
Code Challenge
- Algorithm: SHA256
- Encoding: base64url (no padding)
- Method: Must be S256
- Derived from verifier
State Parameter (CSRF Protection)
The state parameter prevents Cross-Site Request Forgery (CSRF) attacks.How It Works
- Generate: Create random state before initiating OAuth
- Send: Include in OAuth initiation request
- Verify: Validate returned state matches original
State Requirements:
- Minimum 16 characters
- Cryptographically random
- Stored securely (session, not localStorage)
- Validated exactly (case-sensitive)
- Single use only
Secret Key Management
Yourx-secret-key is highly sensitive and must be protected.
Do’s and Don’ts
- ✅ Do
- ❌ Don't
Store Secrets SecurelyRotate Regularly
- Rotate secrets every 90 days
- Rotate immediately if compromised
- Use different keys per environment
Secret Detection
Add pre-commit hooks to prevent accidental commits:Redirect URI Security
The redirect URI (or callback URL) is where users return after authentication, and it’s critical for OAuth security. Incorrect configuration can lead to authorization code theft.What You’ll Learn: This section covers redirect URI requirements, HTTPS vs HTTP, custom schemes for mobile apps, CORS considerations, and validation techniques. For a high-level overview, see the OAuth Quick Start.
What is a Redirect URI?
A redirect URI serves as the callback endpoint where the authorization server returns the user along with the authorization code after successful authentication.Allowed URI Schemes
- HTTPS (Required for Production)
- HTTP (Development Only)
- Custom Schemes (Mobile)
Web applications in production environments MUST use HTTPSHTTPS Requirements:
- Valid SSL/TLS certificate
- TLS 1.2 or higher
- Proper certificate chain configuration
- No mixed content warnings
Whitelist Configuration
Strict Matching Required
Redirect URIs must be exactly whitelisted in your environment configuration. No wildcards or partial matches allowed.All components must match exactly: protocol, domain, path, and port (if specified).
CORS and Redirect URIs
When your frontend application makes OAuth API calls, CORS (Cross-Origin Resource Sharing) settings must align with your redirect URI configuration.Origin Relationship: The redirect URI domain should typically match the origin making OAuth API requests to prevent cross-origin issues.
- Same-Origin (Recommended)
- Cross-Origin
Best Practice: Frontend and redirect URI on the same domainNo CORS configuration needed - requests and callbacks use the same origin.
Security Requirements
Never Use Wildcards
Use HTTPS in Production
Validate on Client
Environment-Specific URIs
Common Redirect URI Pitfalls
Trailing Slash Mismatch
Trailing Slash Mismatch
Problem: Redirect URI with/without trailing slash doesn’t match whitelistSolution: Ensure exact match including trailing slash presence/absence.
Protocol Mismatch
Protocol Mismatch
Problem: HTTP used when HTTPS is whitelisted (or vice versa)Solution: Match protocol exactly; always use HTTPS in production.
Port Number Issues
Port Number Issues
Problem: Explicit port in URI when whitelist doesn’t include itSolution: Omit default ports (80 for HTTP, 443 for HTTPS) unless explicitly required.
Custom Scheme Not Whitelisted
Custom Scheme Not Whitelisted
Problem: Mobile app uses custom scheme without prior approvalSolution: Contact Technical Account Manager to whitelist custom schemes before implementation.
CORS Policy Blocked
CORS Policy Blocked
Problem: Browser blocks OAuth API request due to CORS policySolution:
- Verify your frontend origin is whitelisted for CORS
- Check redirect URI matches whitelisted configuration
- Contact Technical Account Manager to update CORS settings
Client-Side Validation Implementation
Configuration Checklist
1
Determine Redirect URI Scheme
Choose appropriate URI based on platform:
- Web production:
https://yourdomain.com/oauth/callback - Web development:
http://localhost:3000/oauth/callback - Mobile app:
yourapp://oauth/callback(requires technical account manager approval)
2
Request Whitelisting
Contact your Technical Account Manager with:
- Redirect URI(s) for each environment
- Custom URL schemes (if mobile - requires approval)
- CORS origins (if different from redirect URI domain)
3
Implement Callback Handler
Create endpoint to receive authorization code:
- Extract
codeandstatequery parameters - Validate state matches original value
- Exchange code for tokens via
/tokenendpoint
4
Test Complete Flow
Verify end-to-end:
- Initiate OAuth with your redirect URI
- Complete authentication
- Callback receives authorization code
- Code successfully exchanges for tokens
Token Storage Security
How you store tokens is critical for both protecting user data and maintaining the trust users place in your application when they grant authorization. Secure storage prevents unauthorized access to user accounts through stolen tokens.Dual Responsibility: Token security protects both your application’s integrity and the user’s trust. A compromised token allows attackers to act as the user within the scope of granted permissions.
Storage Methods by Platform
- Web Applications
- Mobile Apps
- Server-Side
Best: HTTP-Only CookiesAlternative: Memory Storage⚠️ Avoid localStorage
Common Vulnerabilities
Authorization Code Interception
Authorization Code Interception
Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF)
Attack: Attacker tricks user into initiating OAuth with attacker’s code.Prevention:
- Use state parameter (mandatory)
- Validate state on callback
- Cryptographically random state
Token Leakage via Logs
Token Leakage via Logs
Attack: Tokens exposed in application or server logs.Prevention:
- Never log tokens
- Redact Authorization headers
- Use log sanitization
XSS (Cross-Site Scripting)
XSS (Cross-Site Scripting)
Attack: Malicious script steals tokens from localStorage.Prevention:
- Don’t store tokens in localStorage
- Use HTTP-only cookies
- Implement Content Security Policy
- Sanitize user inputs
Replay Attacks
Replay Attacks
Attack: Reuse intercepted authorization code or token.Prevention:
- Authorization codes are single-use
- Short token lifetimes
- Implement token revocation
- Use HTTPS
Phishing Attacks
Phishing Attacks
Attack: Fake login page steals user credentials.Prevention (Hosted UI):
- Use hosted UI for authentication
- Educate users to verify URL
- Implement domain verification
- Use certificate pinning
- Implement biometric authentication
- Add additional verification steps
Security Checklist
Pre-Production
PKCE Implementation
- Code verifier is 43-128 characters
- SHA256 used for code challenge
- code_challenge_method is S256
- Verifier stored securely
- Verifier validated on exchange
State Parameter
- State is cryptographically random
- State is at least 16 characters
- State stored in secure session
- State validated on callback
- State is single-use
Secret Management
- Secrets in environment variables
- Secrets never in client code
- Secrets never in version control
- Secrets not logged
- Different keys per environment
Redirect URI
- All URIs whitelisted
- HTTPS used in production
- Exact matching implemented
- No wildcards used
- Client-side validation added
Token Storage
- Platform secure storage used
- Not in localStorage (web)
- HTTP-only cookies (web)
- Keychain (iOS)
- EncryptedSharedPreferences (Android)
Error Handling
- Tokens not in error messages
- Secrets not exposed on error
- Sanitized logging implemented
- User-friendly error messages
- Security events logged
Runtime Security
- HTTPS enforced in production
- Certificate validation enabled
- TLS 1.2+ required
- Token refresh before expiry
- Expired refresh token handled
- Token revocation implemented
- Logout clears all tokens
- Session timeout enforced
- Rate limiting implemented
- Security headers set
Monitoring
- Failed authentication monitored
- Token refresh failures logged
- Suspicious activity detected
- Security events alerted
- Access patterns analyzed
Security Headers
Implement these HTTP security headers:Incident Response
If you suspect a security breach:1
Immediate Actions
- Revoke all affected tokens immediately
- Rotate compromised secrets
- Force password reset for affected users
- Disable compromised client keys
2
Investigation
- Review access logs
- Identify scope of breach
- Document timeline
- Preserve evidence
3
Notification
- Notify affected users
- Report to security team
- Comply with regulations (GDPR, etc.)
- Update security documentation
4
Prevention
- Implement additional controls
- Update security practices
- Conduct security review
- Train development team
Additional Resources
OAuth 2.0 Security BCP
Official OAuth 2.0 Security Best Current Practice
OWASP Top 10
Web application security risks
RFC 7636 (PKCE)
PKCE specification
RFC 6749 (OAuth 2.0)
OAuth 2.0 Authorization Framework
