
OAuth 2.0 Misconfigurations and Token Theft
Stealing OAuth 2.0 codes and tokens through redirect_uri bypasses, missing state checks, implicit flow leaks, Referer leaks and scope escalation.
Introduction
Most OAuth 2.0 bugs come from two places. The authorization server trusts values from the request that it should check, or the client application leaves out protections the spec only marks as RECOMMENDED. The redirect_uri gets the most attention: if a code or token is delivered to a URI the attacker controls, that is account takeover. Most OAuth bug bounty reports come down to weak redirect URI checks, a missing state check, or the implicit flow.
RFC 6749 says registered redirect URIs should be compared as simple strings, but enforcement is up to each implementation. Real servers accept prefix matches, path traversal, wildcard subdomains, or a valid callback that itself redirects elsewhere. Each of these can hand the code or token to the attacker.
A client application that does not check state on the callback is open to CSRF. The attacker can link their own identity provider account to the victim's account, then log in as the victim with their own credentials.
Authorization required
Get written permission from the application owner first. OAuth flows also involve a third-party identity provider, and the client's permission does not cover attacks on the provider itself. Keep the testing on the client application's side of the flow.
Impact
- Account takeover through redirect_uri hijacking, where the attacker receives the victim's authorization code or access token
- Account linking CSRF, which silently connects the victim's account to the attacker's social login and gives the attacker a permanent way in
- Access tokens from the implicit flow exposed in browser history and to every script on the callback page
- Privilege escalation by modifying the
scopeparameter during the authorization request - Persistent access if the stolen token has offline_access or refresh token scope
- Mobile application account compromise via deeplink interception or PKCE downgrade
Technical details
redirect_uri validation flaws
The authorization server should compare the supplied redirect_uri with the registered value as an exact string. Shortcuts in that comparison are what you are testing for.
Prefix matching and path traversal. Some servers only check that the supplied URI starts with the registered value.
Registered: https://app.example.com/callback
Supplied: https://app.example.com/callback/../evil
https://app.example.com/callback%2f..%2fevilOpen redirect chaining. The server checks the domain, but a page on that domain has an open redirect. The code or token lands at the legitimate domain, which immediately redirects to the attacker.
https://app.example.com/callback?redirect=https://evil.comIf the application forwards the code or the full URL to the redirect destination (through the Referer header for a code in the query string, through fragment carry-over on redirect for an implicit flow token, or as an explicit parameter), the attacker receives it.
Subdomain takeover as redirect target. If the server allows wildcard subdomain matching and an attacker has claimed an abandoned subdomain, that subdomain becomes a valid redirect target.
Registered: https://*.example.com/callback
Claimed: https://stale-feature.example.com (attacker-controlled via dangling CNAME)
Supplied: https://stale-feature.example.com/callbackState parameter CSRF
The state parameter is a nonce that ties the authorization request to the user session. If the client never sends it, or accepts any value on the callback, account linking CSRF works.
The attack:
Attacker initiates OAuth flow
The attacker starts the authorization flow against the target application with their own identity provider account (a Google account, for example) and captures the authorization URL.
GET /oauth/authorize?response_type=code
&client_id=CLIENT_ID
&redirect_uri=https://app.example.com/callback
&scope=openid+email
&state=ATTACKER_SESSION_STATEAttacker extracts the authorization code
The attacker completes the flow for their own account and receives a code at redirect_uri, but does not let it be exchanged. The code stays valid until it is used or expires.
https://app.example.com/callback?code=ATTACKER_CODE&state=ATTACKER_SESSION_STATEVictim triggered to complete the binding
The attacker sends the victim a link to the callback URL containing their authorization code. If the application doesn't validate that the state matches the victim's session, it exchanges the code and links the attacker's OAuth identity to the victim's account.
<img src="https://app.example.com/callback?code=ATTACKER_CODE" width="1" height="1">Attacker authenticates as victim
The attacker logs in through the provider with their own credentials. The provider issues tokens for the attacker's identity, which the application now maps to the victim's account.
Implicit flow token leakage
The implicit flow (response_type=token) delivers the access token directly in the URL fragment. Browsers never send the fragment in HTTP requests or in the Referer header, but it is visible to JavaScript on the page, saved in browser history, and carried over when the page redirects to a URL without its own fragment.
https://app.example.com/callback#access_token=ya29.a0AfH6SM...&token_type=Bearer&expires_in=3600Any script on the callback page (analytics, CDN-hosted libraries, error tracking) can read window.location.hash and send the token somewhere. It ends up in server logs only when the application's own JavaScript reads it and puts it in a request.
Authorization code interception via referer
When a user lands on a callback URL containing an authorization code and the page loads external resources, the Referer header can carry the full URL including the code. Current browsers default to strict-origin-when-cross-origin and send only the origin cross-site, so this needs an older browser, a page that sets a looser Referrer-Policy, or a same-origin request that ends up logged.
GET /track.js HTTP/1.1
Host: analytics.thirdparty.com
Referer: https://app.example.com/callback?code=4/P7q7W91a-oMsCeLvIaQ...&state=abc123The code is single-use and short-lived (RFC 6749 recommends under 10 minutes), but if it reaches an endpoint the attacker controls, they can try to exchange it before the legitimate client does.
Scope escalation
Authorization requests that accept user-supplied scope values without validating them against the registered client's allowed scopes enable privilege escalation.
# Original request
GET /oauth/authorize?...&scope=read:profile
# Modified request
GET /oauth/authorize?...&scope=read:profile+write:email+admin:orgIf the server grants whatever scope is requested without checking the client's registered allowed scopes, the resulting token carries more permissions than the client should ever have.
Attack tools
Set Burp as the browser proxy and walk through the OAuth flow. The Proxy history shows every redirect and the parameters in each step.
# 1. In Burp Proxy, intercept the initial authorization redirect
# 2. Modify redirect_uri in the intercepted request
GET /oauth/authorize?response_type=code
&client_id=CLIENT_ID
&redirect_uri=https://app.example.com/callback/../attacker # modified
&scope=openid+email
&state=randomstate
Host: accounts.provider.com# Base64-decode JWT access tokens directly in Burp Decoder
# Highlight token, right-click > Send to Decoder > Decode as Base64
# Or use the JSON Web Tokens extension (BApp Store) for automatic parsing
# Extensions > BApp Store > JSON Web Tokens# Remove state from the authorization URL entirely
GET /oauth/authorize?response_type=code
&client_id=CLIENT_ID
&redirect_uri=https://app.example.com/callback
&scope=openid+email
# no state parameter
# If the application proceeds without error, state validation is absent
# Confirm by completing the flow: if successful, CSRF is viable# Set payload position on redirect_uri value
# Payload list: variations of the registered URI
https://app.example.com/callback
https://app.example.com/callback/
https://app.example.com/callback/../
https://app.example.com/callbackx
https://app.example.com/callback?foo=bar
https://app.example.com%2ecallback.evil.com/Detection
Authorization server logs
Alert on redirect_uri values that differ from the registered ones. Most providers log the supplied and registered URIs for each authorization request.
| Log Field | Suspicious Value |
|---|---|
redirect_uri_supplied | Any value not in the registered allowlist |
state | Missing, empty, or reused nonces |
scope | Scopes exceeding the client's registered allowlist |
error | redirect_uri_mismatch repeated across IPs (enumeration) |
Application-side events
The fragment itself never reaches the server, so these searches only hit when client-side code has copied the token into a query string or request body. A hit still means the implicit flow is in use and the token is leaving the browser.
# Fragments are never sent, so look for tokens that ended up in a query string (request line or Referer)
grep -E '[?&]access_token=' /var/log/nginx/access.log
# Or in application error logs where full URLs are captured
grep 'access_token' /var/log/app/request.logSIEM detection queries
index=web_access uri_path="/oauth/callback"
| rex field=uri_query "(?:^|&)state=(?P<state_value>[^&]*)"
| where isnull(state_value) OR state_value=""
| stats count by src_ip, user_agent, uri_query
| where count > 2index=web_access uri_path="/oauth/callback"
| rex field=uri_query "(?:^|&)code=(?P<auth_code>[^&]+)"
| stats count by auth_code, src_ip
| where count > 1
| table auth_code, count, src_ip{
"query": {
"regexp": {
"http.request.referrer": ".*[?&]access_token=.*"
}
}
}Application events to log
| Event | Description |
|---|---|
| OAuth: invalid_redirect_uri | Supplied URI rejected by authorization server |
| OAuth: missing_state | Authorization callback received without state |
| OAuth: code_reused | Authorization code submitted more than once |
| OAuth: scope_exceeded | Requested scope exceeds registered allowlist |
Remediation
redirect_uri validation. The authorization server should do an exact string comparison between the supplied redirect_uri and each registered value. No prefix matching, no regex, no path normalization before comparison. Register the complete URI including path and query string for each client.
REGISTERED_URIS = {
"client_id_123": [
"https://app.example.com/oauth/callback",
]
}
def validate_redirect_uri(client_id: str, supplied_uri: str) -> bool:
allowed = REGISTERED_URIS.get(client_id, [])
# Exact match only: no startswith, no normalization
return supplied_uri in allowedState parameter. The client generates a cryptographically random nonce per authorization request, bind it to the user's session, and reject any callback where the returned state doesn't match what was issued.
import secrets
import hashlib
def generate_state(session_id: str) -> str:
nonce = secrets.token_urlsafe(32)
session.set("oauth_state", nonce)
return nonce
def validate_state(returned_state: str) -> bool:
expected = session.get("oauth_state")
if not expected:
return False
# Use constant-time comparison
return secrets.compare_digest(returned_state, expected)Use authorization code with PKCE instead of the implicit flow.
import secrets
import hashlib
import base64
def generate_pkce_pair():
code_verifier = secrets.token_urlsafe(64) # 43-128 chars, unreserved chars only
digest = hashlib.sha256(code_verifier.encode()).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()
return code_verifier, code_challenge
# Include in authorization request:
# &code_challenge=CODE_CHALLENGE
# &code_challenge_method=S256
# Include in token exchange:
# &code_verifier=CODE_VERIFIEROther hardening:
- Keep authorization code lifetimes short (60 to 120 seconds)
- Invalidate a code the first time it is used and reject any replay
- Restrict
scopevalues server-side per registered client; ignore or reject out-of-allowlist scope requests - Set
Referrer-Policy: no-referreron OAuth callback pages to prevent code/token leakage via the Referer header - Rotate refresh tokens on each use (refresh token rotation) to detect token theft
- Do not offer the implicit grant in new implementations; use
response_type=codewith PKCE
HTTP/1.1 200 OK
Referrer-Policy: no-referrer
Content-Security-Policy: default-src 'self'References
MITRE ATT&CK techniques
- T1528 - Steal Application Access Token
- T1078 - Valid Accounts
- T1566.002 - Phishing: Spearphishing Link
Tools documentation
- PortSwigger Burp Suite
- RFC 6749: The OAuth 2.0 Authorization Framework
- RFC 7636: Proof Key for Code Exchange (PKCE)
- OAuth 2.0 Security Best Current Practice (BCP)
- PortSwigger Web Security Academy: OAuth
Next steps
CSRF: Exploitation and Defense
How CSRF works, how to get past weak token and SameSite defenses, proof-of-concept payloads, and what actually stops it.
Authentication Bypass Techniques
Ways past a login page, from credential attacks and logic flaws to session, JWT, OAuth, MFA and password reset bugs.
Host Header Poisoning
How applications that trust the HTTP Host header end up with poisoned password reset links, poisoned caches, SSRF and access control bypasses.
Business Logic Flaws
Testing for business logic bugs: skipped workflow steps, price and quantity tampering, race conditions, mass assignment and other flaws scanners miss.
NoSQL Injection Attacks
MongoDB operator injection for authentication bypass and blind data extraction in Node.js and PHP applications, plus Redis CRLF injection.
Outdated JavaScript Dependencies
What outdated JavaScript dependencies expose (XSS, prototype pollution, RCE), how to find them with npm audit, Snyk and OSV-Scanner, and how to keep them patched.