Every OAuth and OpenID Connect sign-in ends the same way: the provider sends the browser back to your app with a code in the URL, and your app turns it into tokens. That redirect is the most attacked part of the flow. It passes through a browser you don’t control, it lands on an endpoint anyone can call, and it carries a value worth stealing. Our articles on PKCE and nonces covered the code and the ID token; this one covers the rest of the redirect: the state parameter, the iss parameter, the return URL, and how the provider checks redirect_uri.
As in those articles, every attack runs. A small provider and client in Node, with each protection as an option, let us sign a victim into the attacker’s account, get past state and PKCE with a mix-up attack, and send a code to the attacker’s domain through a loose redirect_uri check. Then we look at the same checks in the identity provider and BFF from our BFF sample.
The short answer#
What the redirect carries#
To run the attacks, we need a provider and a client. The provider issues codes, adds state and iss to the redirect, and compares redirect_uri either exactly or, as an option, by prefix:
// provider.mjs: a minimal authorization server, one per issuer, with just enough to show what the redirect carries.
import { createHash, randomBytes } from "node:crypto";
export function createProvider({ issuer, clients, matchRedirect = "exact", sendIss = true }) {
const codes = new Map();
const registered = (client, uri) =>
matchRedirect === "exact" ? client.redirectUris.includes(uri) : client.redirectUris.some((r) => uri.startsWith(r)); // prefix: the mistake
// GET /authorize, once the user has signed in here. Returns where the provider sends the browser next.
function authorize({ client_id, redirect_uri, state, code_challenge }, user) {
const client = clients[client_id];
if (!client || !registered(client, redirect_uri)) throw new Error("redirect_uri isn't registered");
const code = randomBytes(16).toString("base64url");
codes.set(code, { client_id, redirect_uri, code_challenge, user });
const back = new URL(redirect_uri);
back.searchParams.set("code", code);
if (state !== undefined) back.searchParams.set("state", state);
if (sendIss) back.searchParams.set("iss", issuer); // RFC 9207: says which provider this response is from
return back.href;
}
// POST /token
function token({ code, client_id, client_secret, redirect_uri, code_verifier }) {
const grant = codes.get(code);
codes.delete(code); // one use
if (!grant || grant.client_id !== client_id || grant.redirect_uri !== redirect_uri) throw new Error("invalid_grant");
const { secret } = clients[client_id];
if (secret && client_secret !== secret) throw new Error("invalid_client");
if (grant.code_challenge && createHash("sha256").update(code_verifier ?? "").digest("base64url") !== grant.code_challenge)
throw new Error("invalid_grant: PKCE verifier doesn't match");
return { access_token: randomBytes(16).toString("base64url"), sub: grant.user };
}
return { issuer, authorize, token };
}The client remembers what each browser started in its session, and has an option for each check: how it checks state, whether it uses PKCE, and whether it checks iss. The test script runs a normal sign-in through every combination, so when an attack is refused below, it’s because of the defense, not because sign-in was broken.
// client.mjs: an app's sign-in, with its protections as options, so each attack can run with and without them.
import { createHash, randomBytes } from "node:crypto";
const random = () => randomBytes(32).toString("base64url");
const issued = new Set(); // for state: "global" only (a mistake): every state this server ever issued
export function createClient({ providers, redirect_uri = "https://app.example/callback", state = "session", pkce = false, checkIss = false }) {
return {
// GET /login?provider=…: remember what this browser started, then send it to the provider.
login(session, name) {
const value = state === "fixed" ? "xyz" : random();
if (state === "global") issued.add(value);
const verifier = pkce ? random() : undefined;
session.pending = { provider: name, state: value, verifier };
return {
client_id: providers[name].client_id, redirect_uri, state: value,
code_challenge: verifier && createHash("sha256").update(verifier).digest("base64url"),
};
},
// GET /callback?code=…&state=…&iss=…
callback(session, url) {
const q = new URL(url).searchParams;
const pending = session.pending ?? {};
delete session.pending; // one use, whatever happens next
const ok = {
none: true,
fixed: q.get("state") === "xyz",
global: issued.has(q.get("state")),
session: pending.state !== undefined && q.get("state") === pending.state, // the right check
}[state];
if (!ok) throw new Error("state doesn't match a sign-in this browser started");
const name = pending.provider ?? Object.keys(providers)[0];
const { provider, client_id, secret } = providers[name];
if (checkIss && q.get("iss") !== provider.issuer) throw new Error(`iss is ${q.get("iss")}, expected ${provider.issuer}`);
const { sub } = provider.token({ code: q.get("code"), client_id, client_secret: secret, redirect_uri, code_verifier: pending.verifier });
session.user = `${sub} (${name})`;
},
};
}Login CSRF: signed in as the attacker#
Most attacks on sign-in try to get into the victim’s account. Login CSRF does the reverse: it signs the victim’s browser into the attacker’s account, without the victim noticing. Anything they do next, such as saving a card, uploading a document or connecting a bank account, goes into an account the attacker controls.
The attacker starts a sign-in to your app as themselves, signs in at the provider, and stops at the redirect. The callback URL, with their code, is the payload: they put it in an <img> tag on any page the victim visits, and the victim’s browser calls your callback with it.
// login-csrf.mjs: Mallory signs in as herself, stops before the callback, and makes the victim's browser finish it.
import { createClient } from "./client.mjs";
import { createProvider } from "./provider.mjs";
function attack(label, options) {
const idp = createProvider({ issuer: "https://idp.example", clients: { app: { redirectUris: ["https://app.example/callback"], secret: "s3cret" } } });
const app = createClient({ providers: { idp: { provider: idp, client_id: "app", secret: "s3cret" } }, ...options });
const mallory = {}, victim = {};
const callback = idp.authorize(app.login(mallory, "idp"), "mallory"); // Mallory's own sign-in, up to the redirect...
// ...which she doesn't follow. She puts it in an <img src="…"> on a page the victim visits instead.
try {
app.callback(victim, callback);
console.log(label, `the victim's browser is signed in as ${victim.user}`);
} catch (e) {
console.log(label, "refused:", e.message);
}
}
attack("no state, no PKCE:", { state: "none" });
attack("state: ", { state: "session" });
attack("PKCE, no state: ", { state: "none", pkce: true });no state, no PKCE: the victim's browser is signed in as mallory (idp)
state: refused: state doesn't match a sign-in this browser started
PKCE, no state: refused: invalid_grant: PKCE verifier doesn't matchstate stops it because the victim’s browser never started a sign-in, so its session has no state to match. PKCE stops it for a related reason: the victim’s session has no verifier for Mallory’s code. That’s why RFC 9700 lets a client rely on PKCE for this protection when the provider supports it. In OpenID Connect, the nonce check catches it too, one step later. Use them all; they cost nothing.
state done wrong#
state only works if it’s tied to the browser that started the sign-in. Two common shortcuts aren’t:
// state-mistakes.mjs: the same login CSRF, against three ways of checking state.
import { createClient } from "./client.mjs";
import { createProvider } from "./provider.mjs";
function attack(label, state) {
const idp = createProvider({ issuer: "https://idp.example", clients: { app: { redirectUris: ["https://app.example/callback"], secret: "s3cret" } } });
const app = createClient({ providers: { idp: { provider: idp, client_id: "app", secret: "s3cret" } }, state });
const mallory = {}, victim = {};
const callback = idp.authorize(app.login(mallory, "idp"), "mallory");
try {
app.callback(victim, callback);
console.log(label, `signed in as ${victim.user}`);
} catch (e) {
console.log(label, "refused:", e.message);
}
}
attack("the same state every time: ", "fixed"); // "it's just there to be echoed back"
attack("any state this server issued: ", "global"); // random, but not tied to a browser
attack("this browser's own state: ", "session");the same state every time: signed in as mallory (idp)
any state this server issued: signed in as mallory (idp)
this browser's own state: refused: state doesn't match a sign-in this browser startedA fixed value is echoed back unchanged in the attacker’s callback too. A random value checked against a list of everything the server ever issued accepts the attacker’s own, perfectly valid, value. Only comparing with the state stored in this browser’s session works. Store it server-side, or in a cookie the server protects, and delete it once it’s used, whatever the outcome.
state is also often used to carry data through the sign-in, most commonly where to go afterward. That’s fine if the whole value is protected against tampering, as ASP.NET Core does by encrypting it; it’s not fine if the app decodes a plain value from the URL and trusts what’s inside.
The return URL#
Apps let you sign in from any page and come back to it, so the sign-in link carries a return URL: /login?returnUrl=/orders/7. If the app redirects to whatever it’s given, the sign-in page becomes an open redirect: a link on your trusted domain that lands on the attacker’s, right after a real sign-in, which is the perfect moment for a “please sign in again” phishing page.
The fix is to accept only a path on your own site. String checks are easy to get wrong, because browsers treat //evil.example and /\evil.example as other sites. Resolving the value the way a browser would, and comparing origins, avoids having to list the tricks:
// return-to.mjs: where to send the user after sign-in. Keep it in the session, and allow only a path on this site.
export function safeReturnTo(value, origin = "https://app.example") {
try {
const url = new URL(value, origin); // resolve it the way the browser will
return url.origin === origin ? url.pathname + url.search + url.hash : "/";
} catch {
return "/";
}
}
for (const value of ["/orders?id=7", "https://evil.example/", "//evil.example/", "/\\evil.example/", "javascript:alert(1)", "https://app.example.evil.example/"])
console.log(JSON.stringify(value).padEnd(36), "→", safeReturnTo(value));"/orders?id=7" → /orders?id=7
"https://evil.example/" → /
"//evil.example/" → /
"/\\evil.example/" → /
"javascript:alert(1)" → /
"https://app.example.evil.example/" → /The BFF sample does the same with a string check, and has a test that tries //evil.test/steal:
app.MapGet("/bff/login", (string? returnUrl) =>
Results.Challenge(new AuthenticationProperties { RedirectUri = LocalPath(returnUrl) }, [BffDefaults.OidcScheme]));
// ...
// Only a path on this site, so /bff/login?returnUrl=https://evil.example can't become an open redirect.
static string LocalPath(string? url) =>
url is not null && url.StartsWith('/') && !url.StartsWith("//") && !url.StartsWith("/\\") ? url : "/";Mix-up: when there’s more than one provider#
Many apps offer several providers: “Sign in with Google, Microsoft or GitHub”, or any provider a business customer configures. A mix-up attack uses that. One of the providers is the attacker’s, or has been compromised. The victim starts a sign-in with it, and it sends their browser on to an honest provider, keeping your app’s state and PKCE challenge. The victim is already signed in there, so the honest provider sends them back to your app with a code for their real account.
Your app’s session says this sign-in went to the attacker’s provider, so that’s where it redeems the code, verifier included. The attacker now has a code and verifier for the victim’s account at the honest provider:
// mix-up.mjs: the app offers two providers, and one is the attacker's. State and PKCE are both on, and both pass.
import { createClient } from "./client.mjs";
import { createProvider } from "./provider.mjs";
function attack(label, checkIss) {
const redirectUris = ["https://app.example/callback"]; // one callback for every provider
const good = createProvider({ issuer: "https://good.example", clients: { "app-at-good": { redirectUris } } }); // a public client
let stolen;
const evil = { issuer: "https://evil.example", token: (request) => { stolen = request; throw new Error("invalid_grant"); } };
const app = createClient({
providers: { good: { provider: good, client_id: "app-at-good" }, evil: { provider: evil, client_id: "app-at-evil" } },
pkce: true, checkIss,
});
// Alice picks "Sign in with Evil" (or the attacker starts that sign-in for her). Evil's authorization endpoint sends
// her browser on to Good's, with Good's client_id and the app's own state and code_challenge. She's signed in at
// Good already, so Good sends her back to the app with a code for her Good account.
const alice = {};
const request = app.login(alice, "evil");
const callback = good.authorize({ ...request, client_id: "app-at-good" }, "alice");
// The app's session says this sign-in went to Evil, so it redeems the code there, verifier and all.
try {
app.callback(alice, callback);
} catch (e) {
if (!stolen) return console.log(label, "refused:", e.message);
}
const { sub } = good.token({ ...stolen, client_id: "app-at-good" }); // the attacker redeems it at Good
console.log(label, `the attacker has tokens for ${sub} at Good`);
}
attack("state + PKCE: ", false);
attack("state + PKCE + iss:", true);state + PKCE: the attacker has tokens for alice at Good
state + PKCE + iss: refused: iss is https://good.example, expected https://evil.examplestate passed, because the victim’s own browser did start this sign-in. PKCE passed too, and worse, the app handed the verifier to the attacker. Neither can tell the app which provider actually answered. That’s what the iss parameter is for: RFC 9207 (2022) has the provider add its issuer identifier to every authorization response, and the app compares it with the provider it sent the user to. The code never reaches the attacker. Our sample’s identity provider sends it on every redirect:
// Until the client and redirect_uri check out, errors are shown here: redirecting would be an open redirect.
if (client is null) return Html(Pages.Error("Unknown client_id."), 400);
if (redirectUri is null || !client.RedirectUris.Contains(redirectUri, StringComparer.Ordinal))
return Html(Pages.Error("This redirect_uri isn't registered for the client."), 400);
// ...
// "iss" is RFC 9207: it tells the client which provider the code came from.
return Results.Redirect(QueryHelpers.AddQueryString(redirectUri,
new Dictionary<string, string?> { ["code"] = code, ["state"] = state, ["iss"] = Options().Issuer }));RFC 9700 requires a mix-up defense for any client that uses more than one provider. Checking iss is the main one; a provider that supports it says so with authorization_response_iss_parameter_supported in its metadata. The alternative is a different redirect_uri for each provider, so the callback itself says which provider the response is for. If your app only ever uses one provider, mix-up doesn’t apply, but checking iss is still cheap insurance.
In this example, the app is a public client, so the stolen code and verifier were all the attacker needed. A confidential client’s secret would stop the attacker redeeming the code directly, but the code still leaked, and RFC 9700 doesn’t treat the secret as a mix-up defense.
redirect_uri: exact matching only#
The provider decides where to send the code by checking the redirect_uri against what the app registered. Some providers have allowed wildcards or prefixes, and some apps register just their origin to make development easier. Here, the app registered https://app.example, and the provider checks the prefix:
// redirect-uri.mjs: the app registered just its origin, and the provider compares redirect_uri as a prefix.
import { createHash, randomBytes } from "node:crypto";
import { createProvider } from "./provider.mjs";
function attack(label, matchRedirect) {
const idp = createProvider({ issuer: "https://idp.example", matchRedirect, clients: { spa: { redirectUris: ["https://app.example"] } } });
// The attacker builds a sign-in link for the app, with their own PKCE pair and their own redirect_uri.
const verifier = randomBytes(32).toString("base64url");
const link = {
client_id: "spa", redirect_uri: "https://app.example.evil.example/steal", state: "anything",
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
};
try {
const landed = new URL(idp.authorize(link, "alice")); // Alice opens it; she's already signed in at the provider
const code = landed.searchParams.get("code");
const { sub } = idp.token({ client_id: "spa", redirect_uri: link.redirect_uri, code, code_verifier: verifier });
console.log(label, `code delivered to ${landed.host}; the attacker has tokens for ${sub}`);
} catch (e) {
console.log(label, "refused:", e.message);
}
}
attack("prefix match:", "prefix");
attack("exact match: ", "exact");prefix match: code delivered to app.example.evil.example; the attacker has tokens for alice
exact match: refused: redirect_uri isn't registeredhttps://app.example.evil.example starts with https://app.example, and it’s a domain the attacker can own. Note that PKCE didn’t help: the attacker built the sign-in link, so they made the PKCE pair and had the verifier all along. PKCE protects a sign-in the app started, not one the attacker started.
RFC 9700 requires providers to compare redirect URIs with exact string matching (the one exception is the port of a loopback address for native apps, as in RFC 8252). As a client, register every full callback URL, path included, and don’t rely on the provider being strict: a redirect URI on a path that also hosts an open redirect, or user content, can leak codes even with exact matching. The sample’s identity provider compares with StringComparer.Ordinal, and shows an error itself, rather than redirecting, until the client and redirect_uri check out; redirecting an error to an unregistered URI would be an open redirect of its own.
The checklist#
| Check | Who | Stops |
|---|---|---|
state matches this browser’s session, used once | App | Login CSRF |
| PKCE (S256) | App and provider | Stolen and injected codes; login CSRF too |
nonce in the ID token | App | Injected or replayed ID tokens |
iss matches the provider the user was sent to | App | Mix-up |
| Return URL is a path on this site | App | Open redirect after sign-in |
redirect_uri matched exactly | Provider | Codes sent to the attacker |
| Errors before the client is verified are shown, not redirected | Provider | Open redirect from the provider |
Most frameworks do the app’s side for you, so the practical job is to check what yours validates: whether it binds state to the session, supports iss if you have several providers, and how it handles return URLs. ASP.NET Core’s OpenID Connect handler encrypts its state and ties it to a correlation cookie; the BFF sample adds the return-URL check.
What we tested#
Every JavaScript example above runs unchanged on Node 24 in Docker, from tests/oauth-redirect-security/test.sh:
- The normal sign-in works in all 32 client and provider configurations the attacks use, with two providers each, and codes work once.
- The four attacks print exactly the outputs shown, five runs each.
- The return-URL check gives the table above, and ten more tricky values either stay on the site as paths or fall back to
/. - The C# excerpts are checked line by line against the BFF sample, and its 15 integration tests pass on .NET 10, including the ones for an unregistered
redirect_uriand a return URL of//evil.test/steal.
FAQ#
If I use PKCE, do I still need state?
RFC 9700 says a client may rely on PKCE for CSRF protection if the provider supports PKCE. In practice, keep both: your framework sends state anyway, it’s often how the return URL is carried safely, and it protects you if a provider quietly doesn’t enforce PKCE.
Isn’t the ID token’s iss claim enough to stop mix-up?
No. You only see the ID token after redeeming the code, and in a mix-up the app redeems it at the attacker’s provider, which has already received the code by then. The iss parameter is checked before the code leaves the app.
Does login CSRF matter if my app has nothing valuable in it?
It matters whenever users enter something: payment details, documents, search history, linked accounts. All of it ends up visible to the attacker, who owns the account the victim was signed into.
What about the logout redirect?
The same rules apply: post_logout_redirect_uri must be registered and matched exactly, or logout becomes an open redirect. The sample’s identity provider only redirects after logout to a registered URI, and only when the ID token hint identifies the client.
How can I see what’s in the iss of a token?
Paste the ID token into our JWT decoder: the iss claim should be the same issuer the iss parameter named on the redirect.
Get the code
- bff-sample on GitHub: an ASP.NET Core identity provider that matches redirect_uri exactly and sends iss on every redirect, and a BFF whose sign-in never redirects off the site, with integration tests for both.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode an ID token and compare its iss claim with the iss parameter the redirect carried.