Common OAuth Flaws: redirect_uri, state and the Implicit Flow
OAuth's cryptography is rarely what breaks. What breaks is the glue: an authorization server that matches redirect URIs loosely, a client that forgets state, a single-page app still on the implicit flow, a "Sign in with…" button that trusts an e-mail address. Each of these has led to real account takeovers on large platforms, usually by stealing an authorization code or token through a redirect the attacker controls. This lesson takes the three most common flaws apart in Python models of the server and client, then lists the rest with their detection and fix. Concepts come from OAuth 2.0 and OpenID Connect and PKCE.
Flaw 1: loose redirect_uri matching
The authorization server sends the code to whatever redirect_uri it accepts. If an attacker can make it accept a URI they control, they get the victim's code (and, without PKCE, the account). Servers have implemented "matching" in many creative ways. The example tests five matchers against the registered URI https://shop.lab.test/callback and seven candidate URIs an attacker might send.
import re
from urllib.parse import urlsplit
REGISTERED = "https://shop.lab.test/callback"
MATCHERS = {
"prefix": lambda u: u.startswith(REGISTERED),
"substring": lambda u: "shop.lab.test" in u,
"host-only": lambda u: urlsplit(u).hostname == "shop.lab.test",
"regex": lambda u: re.match(r"https://shop.lab.test/callback", u) is not None,
"exact": lambda u: u == REGISTERED,
}
CANDIDATES = [
"https://shop.lab.test/callback",
"https://shop.lab.test/callback/../redirect?to=https://evil.example",
"https://shop.lab.test/callback.evil.example/",
"https://shop.lab.test.evil.example/callback",
"https://evil.example/?shop.lab.test",
"https://shopXlab.test/callback",
"https://shop.lab.test/user-uploads/attacker.html",
]
print(f"{'candidate':66}" + "".join(f"{m:>10}" for m in MATCHERS))
for c in CANDIDATES:
print(f"{c:66}" + "".join(f"{'ACCEPT' if f(c) else '-':>10}" for f in MATCHERS.values()))candidate prefix substring host-only regex exact
https://shop.lab.test/callback ACCEPT ACCEPT ACCEPT ACCEPT ACCEPT
https://shop.lab.test/callback/../redirect?to=https://evil.example ACCEPT ACCEPT ACCEPT ACCEPT -
https://shop.lab.test/callback.evil.example/ ACCEPT ACCEPT ACCEPT ACCEPT -
https://shop.lab.test.evil.example/callback - ACCEPT - - -
https://evil.example/?shop.lab.test - ACCEPT - - -
https://shopXlab.test/callback - - - ACCEPT -
https://shop.lab.test/user-uploads/attacker.html - ACCEPT ACCEPT - -
Only exact string comparison rejects all six attacks. Prefix matching lets the attacker append a path that, once normalised, reaches an open redirect on the client (/redirect?to=…), which forwards the browser, code and all, to the attacker; or a path such as /callback.evil.example/ that merely starts the same way. Substring checks accept any domain mentioning the client. The regex forgot that . matches any character and that re.match only anchors the start. Host-only matching hands the code to any page on the client's host, including user uploads and any open redirect. RFC 9700 and OAuth 2.1 therefore require exact matching of registered redirect URIs (with a narrow exception for port numbers on native-app loopback redirects).
Flaw 2: no state, so login CSRF
state binds the callback to this browser's request. Without it, an attacker can start a sign-in with their own account, stop before the callback, and make the victim's browser load the callback URL with the attacker's code. The victim is now signed in to the client as the attacker: anything they save (a card, a document, search history) lands in the attacker's account. The model shows the client with and without a state check.
class Client:
def __init__(self, check_state):
self.check_state, self.pending_state, self.user = check_state, None, None
def start_login(self, state):
self.pending_state = state
def callback(self, code_owner, state):
if self.check_state and (self.pending_state is None or state != self.pending_state):
return "rejected: state does not match a request from this browser"
self.pending_state, self.user = None, code_owner
return f"signed in as {code_owner}"
for check in (False, True):
victim_browser = Client(check_state=check)
# The attacker obtained a code for THEIR account and a state from THEIR own browser.
result = victim_browser.callback(code_owner="attacker", state="attacker-state-123")
print(f"state check {'on ' if check else 'off'}: forced callback -> {result}")
if victim_browser.user:
print(" victim saves a payment card ->", f"stored in {victim_browser.user}'s account")
victim_browser.start_login("victim-state-9f2")
print(f"state check {'on ' if check else 'off'}: genuine callback -> {victim_browser.callback('victim', 'victim-state-9f2')}")state check off: forced callback -> signed in as attacker
victim saves a payment card -> stored in attacker's account
state check off: genuine callback -> signed in as victim
state check on : forced callback -> rejected: state does not match a request from this browser
state check on : genuine callback -> signed in as victim
PKCE also defeats this when the verifier is stored per browser session (the attacker's code was issued for a challenge the victim's browser never created), which is why RFC 9700 lets PKCE substitute for state against CSRF; OIDC's nonce does the same for ID tokens. Using all three costs nothing.
Flaw 3: the implicit flow
The implicit flow (response_type=token) returns the access token directly in the redirect URL fragment: https://app.lab.test/cb#access_token=…. It was designed for browsers before CORS existed. Its problems:
- The token sits in the address bar and browser history, and is readable by every script on the page and by browser extensions.
- An open redirect on the client forwards the fragment (browsers keep fragments across redirects) to the attacker.
- There is no way to bind the token to the client: no code exchange, no PKCE, no refresh-token rotation.
The fix is the authorization code flow with PKCE, which every modern browser supports. RFC 9700 says clients should not use the implicit flow, and OAuth 2.1 removes it.
More flaws, in one table
| Flaw | Mechanism | Detection | Fix |
|---|---|---|---|
| Open redirect on the client | used as the second hop of flaw 1 | test every redirect parameter on the client | fix the redirect; exact redirect_uri |
Code or token in Referer |
callback page loads third-party resources before cleaning the URL | look at outgoing requests from the callback | Referrer-Policy: no-referrer on the callback; clean the URL first (ExcelTAD replaces the address bar before doing anything else) |
| Login with unverified e-mail | client links accounts by e-mail from a provider that doesn't verify it | create an IdP account with the victim's address | key users by (iss, sub); link only email_verified addresses, after the user proves control |
| Access token as login proof | a token issued to another app is accepted | present a token from another client | log in with the ID token; check its aud |
| Scope upgrade at the token endpoint | client asks for more scopes in the exchange than were consented | change scope in the token request |
AS issues only the consented scopes |
| Refresh token theft from a SPA | long-lived refresh token in browser storage | inspect storage, lifetimes | rotation with reuse detection, short lifetimes, sender-constrained tokens (DPoP), or a backend-for-frontend |
| Mix-up | a client with several ASes sends a code to the wrong one | multiple-issuer clients | the iss response parameter (RFC 9207), as ExcelTAD requires |
How OAuth flaws are found (detection)
In an authorised test, map every OAuth request with an intercepting proxy, then: vary redirect_uri systematically (the candidate list above is a start), remove state, nonce and code_challenge one at a time, replay codes, change response_type to token and code token to see if the AS still offers the implicit flow, and check where tokens end up (URL, Referer, storage, logs). On the server side, alert on redirect URI mismatches and code reuse.
How they are fixed
Exact redirect URIs, authorization code + PKCE (S256) for every client, state and nonce checked, iss checked, ID token fully validated, no implicit or password grants, refresh-token rotation, and users keyed by iss + sub.
Pitfalls
- Registering wildcard redirect URIs "for preview deployments": every preview host becomes a code sink.
- Checking
stateonly when present: the attacker simply leaves it out. - Believing PKCE fixes redirect_uri flaws: an attacker who gets the browser to their page can often start a fresh flow there; exact matching is still required.
Practice
1. Which candidate in the matcher table did the "host-only" matcher accept that "prefix" didn't, and why is it dangerous?
https://shop.lab.test/user-uploads/attacker.html: same host, different path. If users can host pages there (uploads, profiles, an open redirect), the attacker's page receives the code.
2. Write the one-line fix for the regex matcher, then say why exact comparison is still better.
re.fullmatch(re.escape(REGISTERED), u), which is just exact comparison in disguise. Plain u == REGISTERED is clearer and can't be "improved" back into a bug.
Test yourself
How must an authorization server compare redirect URIs?
- Prefix match
- Same host is enough
- Exact string match against the registered URIs
- Regex
What does a missing state check allow in the second example?
- Token theft
- Login CSRF: the victim is signed in as the attacker
- SQL injection
- Nothing
Why is the implicit flow discouraged?
- It is slower
- Tokens appear in the URL fragment, readable by scripts and forwarded by redirects, with no PKCE or code exchange
- It needs a client secret
- It doesn't support scopes
A client links a Google-like login to an existing account whenever the e-mail matches. What is the risk?
- None
- An attacker with an IdP account claiming the victim's unverified e-mail takes over the victim's account
- Slow logins
- Token expiry