OAuth 2.0
What is OAuth 2.0?
OAuth 2.0 (Open Authorization 2.0) is an open standard protocol for delegated authorization. It allows third-party services to access user resources without exposing credentials, enabling secure, limited access to protected data. OAuth 2.0 is widely used by platforms like Google, Facebook, and Microsoft to enable "Login with..." functionality.
How OAuth 2.0 Works
OAuth 2.0 defines four primary roles:
- Resource Owner: The user who owns the data (e.g., you)
- Client: The application requesting access (e.g., a mobile app)
- Authorization Server: Issues access tokens (e.g., Google's auth server)
- Resource Server: Hosts the protected resources (e.g., Google Drive)
The OAuth 2.0 Flow
- Authorization Request: Client asks the user for permission
- Authorization Grant: User approves and receives an authorization code
- Token Request: Client exchanges the code for an access token
- Resource Access: Client uses the token to access protected resources
User → (1) Request Access → Client
Client → (2) Redirect to Auth Server → User
User → (3) Approve → Auth Server
Auth Server → (4) Authorization Code → Client
Client → (5) Exchange Code for Token → Auth Server
Auth Server → (6) Access Token → Client
Client → (7) Access Resources → Resource Server
OAuth 2.0 Grant Types
OAuth 2.0 supports multiple grant types for different scenarios:
| Grant Type | Use Case | Security Level | Complexity |
|---|---|---|---|
| Authorization Code | Web apps, server-side apps (most secure) | High | Medium |
| Implicit | Single-page apps (deprecated in OAuth 2.1) | Low | Low |
| Resource Owner Password Credentials | Trusted first-party apps (not recommended) | Medium | Low |
| Client Credentials | Machine-to-machine communication (no user involved) | High | Low |
| Refresh Token | Obtain new access tokens without user interaction | High | Medium |
| PKCE (Proof Key for Code Exchange) | Mobile and single-page apps (enhanced security) | Very High | Medium |
Key OAuth 2.0 Components
1. Access Tokens
- Short-lived credentials (typically JWT) that grant access to resources
- Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
2. Refresh Tokens
- Long-lived credentials used to obtain new access tokens
- Should be stored securely (e.g., HTTP-only cookies)
3. Scopes
- Define the specific permissions granted (e.g.,
read:email,write:profile) - Example:
scope=email profile openid
4. Redirect URIs
- Where the authorization server sends the user after approval
- Must be pre-registered to prevent phishing
OAuth 2.0 Security Risks
1. Token Theft
- Attackers steal access tokens to impersonate users
- Mitigation: Use short-lived tokens and HTTPS
2. CSRF Attacks
- Attackers trick users into authorizing malicious apps
- Mitigation: Use state parameters and PKCE
3. Open Redirects
- Malicious redirect URIs send users to phishing sites
- Mitigation: Validate redirect URIs against a whitelist
4. Token Leakage
- Tokens exposed in logs, URLs, or browser history
- Mitigation: Use HTTP-only and Secure flags for cookies
5. Insecure Storage
- Tokens stored insecurely on client devices
- Mitigation: Use secure storage (e.g., Keychain, Android Keystore)
OAuth 2.0 Best Practices
1. Always Use HTTPS
- OAuth 2.0 requires TLS to protect tokens in transit
2. Prefer Authorization Code + PKCE
- The most secure flow for mobile and single-page apps
- Prevents authorization code interception
3. Validate Redirect URIs
- Ensure redirect URIs match pre-registered values
- Example (Node.js):
const allowedRedirects = ['https://yourapp.com/callback']; if (!allowedRedirects.includes(redirectUri)) { throw new Error('Invalid redirect URI'); }
4. Use Short-Lived Tokens
- Access tokens should expire quickly (e.g., 1 hour)
- Use refresh tokens for long-lived access
5. Implement Token Revocation
- Allow users to revoke access (RFC 7009)
- Example:
/revokeendpoint
6. Secure Token Storage
- Store tokens in HTTP-only, Secure, SameSite cookies
- Avoid localStorage (vulnerable to XSS)
7. Monitor and Log
- Track token usage to detect anomalies
- Log failed authentication attempts
OAuth 2.0 vs. OpenID Connect (OIDC)
| Feature | OAuth 2.0 | OpenID Connect (OIDC) |
|---|---|---|
| Purpose | Authorization (access to resources) | Authentication (identity) |
| Tokens | Access token | Access token + ID token |
| User Info | Not included | Standardized user claims |
| Flows | Multiple grant types | Built on OAuth 2.0 flows |
| Use Case | API access | User login and profile data |
Real-World Examples
Social Login
- "Login with Google" uses OAuth 2.0 to access your profile
- Scopes:
openid email profile
Cloud Storage
- Apps like Dropbox use OAuth 2.0 to access Google Drive files
- Scopes:
https://www.googleapis.com/auth/drive.readonly
Banking APIs
- Fintech apps use OAuth 2.0 to access bank account data
- Requires strong customer authentication (SCA) under PSD2
OAuth 2.0 Extensions and Standards
- OAuth 2.1: Simplifies and secures OAuth 2.0 (deprecates implicit flow)
- PKCE (RFC 7636): Enhances security for public clients
- JWT Profile (RFC 9068): Standardizes JWT-based access tokens
- Token Introspection (RFC 7662): Validates tokens with the auth server
- Token Revocation (RFC 7009): Allows clients to revoke tokens
Related Concepts
- OpenID Connect (OIDC): Identity layer built on OAuth 2.0
- JWT (JSON Web Token): Common token format used in OAuth 2.0
- SAML (Security Assertion Markup Language): Alternative authentication protocol
- Multi-Factor Authentication (MFA): Additional security layer for OAuth flows
- Session Management: Maintaining secure sessions with OAuth tokens
- WebSockets Security: Securing real-time communication with OAuth
- Cross-Site Request Forgery (CSRF): Attack prevented by OAuth best practices
Further Reading
NoSQL Injection
NoSQL Injection is a security vulnerability that allows attackers to inject malicious NoSQL queries into database operations, bypassing authentication and extracting data.
OAuth Misconfiguration
OAuth misconfiguration vulnerabilities allow attackers to bypass authentication, escalate privileges, or access sensitive user data by exploiting improper implementation of the OAuth 2.0 protocol.
