Skip to content
OAuth / SSO Write-up Advanced

When PKCE Isn’t Enough: How an OAuth Redirect URI Flaw Can Lead to Account Takeover

The OAuth/OIDC implementation on a Keycloak-based banking identity platform had insufficiently restrictive redirect URI validation. Under the observed conditions, an attacker who initiated an authorization request with their own PKCE verifier could have the authorization code delivered to an untrusted destination after the victim authenticated, potentially allowing the attacker to redeem the code.

Sanaullah Aman Korai Follow

Published on sanaullahamankorai.medium.com

Cybersecurity

Sanaullah Aman Korai, on sanaullahamankorai.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 7 min read.

Context

OAuth 2.0 lets an application obtain access to protected resources without collecting the user's password directly, and OpenID Connect (OIDC) extends it with an identity layer so applications can authenticate users and receive information about their identity. In the authorization code flow, the user is redirected to an identity provider, signs in, and is redirected back to the client application with an authorization code. The client exchanges that code for tokens, which can then be used to access authorised resources.

Figure 1: A simplified authorization code flow involving the browser, client application, identity provider, and resource server. From the original on sanaullahamankorai.medium.com

Figure 1: A simplified authorization code flow involving the browser, client application, identity provider, and resource server.

PKCE, defined in RFC 7636, adds a verification step to that exchange. The client generates a random value called a code_verifier, derives a code_challenge from it, and includes the challenge in the initial authorization request. When the client later exchanges the authorization code for tokens, it presents the original verifier, and the authorization server checks that it matches the challenge associated with the code. If someone intercepts the authorization code without the matching verifier, they should not be able to redeem it.

The assessment described here was carried out against a banking identity platform built on Keycloak. The flow under review had PKCE enabled, but redirect URI validation was not sufficiently restrictive. Under the conditions observed, that weakness could allow an authorization code to be delivered to an untrusted destination after a user authenticated. PKCE itself was not the problem; the failure sat in another part of the authorization flow.

Setup

The work was done during an authorised assessment of the banking identity platform. The report does not describe specific accounts, roles, tooling or product versions beyond the platform being built on Keycloak. The precondition that matters is the configuration under test: an OAuth/OIDC client with PKCE enabled and redirect URI validation that is broader than it should be.

Finding it

The starting observation is a distinction that is easy to miss. PKCE does not decide whether the requested redirect destination is trustworthy. The authorization server has to enforce that separately by validating the redirect_uri. These two controls solve different problems, and both need to work correctly.

So the question to ask of any deployment is whether an authorization request can direct the response to a destination that the client and identity provider should not trust. In this platform, the report says the redirect URI validation was not restrictive enough, and under the conditions observed this could allow the response to reach an untrusted destination.

Exploitation

Step 1: Generate your own verifier and challenge

An attacker who can influence the redirect URI in an authorization request does not need to steal the victim's verifier. They generate their own PKCE verifier and challenge before creating the request, and they initiate the authorization request themselves, supplying the challenge associated with their own verifier.

Step 2: Get the victim to authenticate

The victim's login can be entirely legitimate. Their password and one-time password can be correct, and the identity provider can authenticate them successfully. Nothing about the victim's credentials is abused.

Step 3: The code goes to the wrong destination

If the identity provider accepts an unauthorised redirect destination, it sends the authorization code to that destination after the user successfully authenticates. The failure occurs at the point where the authorization server sends the authorization response to a destination that should not have been allowed.

Figure 2: An illustrative attack flow. The identity provider accepts an untrusted redirect destination, potentially exposing the authorization code. From the original on sanaullahamankorai.medium.com

Figure 2: An illustrative attack flow. The identity provider accepts an untrusted redirect destination, potentially exposing the authorization code.

Step 4: Redeem the code

Because the attacker generated the verifier, they already know it. If the authorization server accepts the redirect URI and the remaining checks permit the exchange, the attacker may be able to redeem the code. Whether that succeeds depends on the server's other checks, which the report does not enumerate.

Root cause

OAuth clients register redirect URIs with the identity provider, and during authorization the requested redirect URI must be validated against the client's registered configuration and the applicable protocol requirements. Problems arise when validation rules are too broad, such as unsafe wildcard configurations or matching logic that accepts destinations outside the intended trust boundary. A team might believe that allowing a broad range of subdomains is convenient, but if an attacker can control one of those subdomains, or otherwise make an unauthorised destination satisfy the validation rule, the configuration may expose the authorization response.

The presence of a wildcard does not automatically make an implementation vulnerable. The actual risk depends on the matching rules, which destinations are trusted, and whether an attacker can control or exploit an accepted destination. In this case the validation was not restrictive enough, and PKCE did not compensate for it, because PKCE was never designed to decide where the response may go.

Short-lived, single-use authorization codes do not fix this either. They reduce the opportunity to reuse an intercepted code, but if a code reaches an untrusted destination and the attacker holds the matching verifier, an automated exchange may be possible within the code's validity period, subject to the server's other checks. Expiry and single-use enforcement are useful layers of defence, not substitutes for validating the redirect URI.

Permissive CORS is a related but separate concern. CORS determines whether browser-based JavaScript from one origin can read responses from another. An overly permissive policy on the token endpoint, for example one that reflects arbitrary origins, can introduce additional risk for browser-based clients, depending on the endpoint's configuration and the browser's security rules. But a permissive CORS policy does not by itself prove account takeover, and it is not always necessary for an attacker to redeem a code outside the browser. It is better documented as a separate finding or contributing weakness when the evidence supports it, rather than treated as the root cause of every OAuth redirect vulnerability.

Impact

Under the conditions observed, the weakness could allow an authorization code to be delivered to an untrusted destination after a victim authenticates normally, and, holding the matching verifier, an attacker may be able to redeem it if the remaining checks permit the exchange. The victim's password and one-time password can be entirely correct throughout; the failure is in where the response is sent, not in how the user authenticated.

The report is careful about the limits. Observing a suspicious redirect is not the same as demonstrating token theft, and obtaining a token is not automatically proof of access to every part of an account. Whether the weakness exposes an authorization code, allows token issuance, or provides access to protected resources are distinct stages and should be reported accurately.

Fix

The authorization server should reject an authorization request when its redirect URI is not permitted for the requesting client, and that decision must happen before the server issues an authorization response. An unapproved destination should not receive an authorization code. PKCE should remain enabled; the goal is to combine it with proper redirect URI validation, appropriate token endpoint protections, and secure client configuration.

The report does not state which changes, if any, were made to the platform after the assessment. The review it recommends covers the whole authorization flow rather than whether a single feature is switched on:

  • Registered redirect URIs: remove unused entries and avoid unnecessarily broad matching rules.
  • Redirect validation: confirm that unauthorised destinations are rejected and that validation follows the relevant protocol requirements.
  • PKCE enforcement: confirm that the authorization server requires and verifies the correct code_verifier, using S256 where appropriate.
  • Authorization code handling: check that codes are short-lived, bound to the appropriate client and redirect URI, and accepted only once.
  • CORS policy: verify that only the necessary origins are allowed and that arbitrary origins are not reflected without justification.
  • Token scope and audience: ensure that tokens grant only the intended permissions and are accepted only by their intended resource servers.
  • Impact verification: in an authorised test environment, determine whether the weakness exposes an authorization code, allows token issuance, or provides access to protected resources.

The report also gives a teaching example of an explicit redirect URI allowlist in Python, noting that it illustrates the principle and is not a replacement for the identity provider's built-in validation:

Python
REGISTERED_REDIRECT_URIS = {    "https://app.example.test/oauth/callback"}
Python
def is_allowed_redirect_uri(redirect_uri: str) -> bool:    return redirect_uri in REGISTERED_REDIRECT_URIS

In a real implementation, redirect URI validation should follow the applicable OAuth/OIDC requirements and the identity provider's supported configuration. Teams should not replace built-in validation with an improvised check without reviewing the protocol requirements.

Variants to test

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

A security researcher was hired to test a banking platform's login system. That system was built on a piece of software called Keycloak, which is a common tool for managing who can sign in to what. The login used a standard called OAuth 2.0, plus an extension of it called OpenID Connect (OIDC).

OAuth is the plumbing behind the "Sign in with Google" or "Sign in with your bank" buttons you have seen. It lets one website ask another, trusted website to confirm who you are, without the first website ever seeing your password. The trusted website is called the identity provider. The website you are trying to use is called the client application.

The platform had a security feature called PKCE switched on. PKCE is designed to stop a particular kind of theft: someone grabbing the short-lived pass (an authorization code) that the identity provider hands back after you log in, and swapping it for a longer-lived key (a token) that gives access to your account. PKCE is a good feature, and it was enabled.

But the platform had a second, separate weakness. When the identity provider finished logging you in, it had to send that short-lived pass somewhere. The place it sends it is called the redirect URI. The platform's rules for deciding which redirect URIs were acceptable were too loose. Because of that, under the conditions observed, the weakness could allow the pass to be delivered to an untrusted destination rather than to the real application.

PKCE did not save the day, because PKCE was never meant to answer the question "is this destination trustworthy?". That is a different job, done by checking the redirect URI. The two controls solve different problems, and both have to work.

The researcher's conclusion is not that PKCE is useless. It is that switching PKCE on and stopping there leaves a gap. This article walks through the whole flow from zero, explains each concept as it appears, and shows what the researcher would check on any similar system.

1. A quick refresher on OAuth and PKCE

What OAuth is, in everyday terms

Imagine a hotel. You want a guest to be able to open your room door, but you do not want to give them your master key, and you do not want to hand over your passport at the front desk on their behalf. So the hotel gives your guest a temporary key card, valid for one door and one day. OAuth is that idea for websites.

An application wants to reach some protected resource, for example your list of bank transactions. Instead of asking you for your bank password, it sends you to the bank's own login page. You sign in there. The bank then gives the application a limited, temporary credential. The application uses that credential to fetch what it needs.

Two terms worth pinning down now:

  • API (Application Programming Interface): a way for one piece of software to ask another piece of software to do something, in a fixed, agreed format. Think of it as a service counter: you hand over a request in the expected form, and you get back a response. You never go behind the counter.
  • Token: a string of characters that acts like a temporary pass. Whoever holds a valid token can usually do whatever the token permits, which is why tokens are treated like secrets.

OIDC is OAuth with an identity layer added on top. Plain OAuth is about access (can this app read your data?). OIDC adds the question of identity (who is this user, and what is their name or email?). Many systems use the two together and people often say "OAuth" when they mean both.

The authorization code flow

In the most common OAuth pattern, called the authorization code flow, the steps are:

  1. You click "Sign in with the bank" on the client application.
  2. Your browser is sent to the identity provider (the bank's login service).
  3. You sign in there, with your password and possibly a one-time password.
  4. The identity provider sends your browser back to the client application, carrying a short-lived string called an authorization code.
  5. The client application takes that code and exchanges it, server to server, for tokens.
  6. The client application uses the tokens to call the resource server and fetch your data.
Figure 1: A simplified authorization code flow involving the browser, client application, identity provider, and resource server. From the original on sanaullahamankorai.medium.com

Figure 1: A simplified authorization code flow involving the browser, client application, identity provider, and resource server.

The diagram shows the four parties: your browser, the client application, the identity provider, and the resource server (the system that actually holds the data). The arrows trace the loop above. The important detail for this story is step 4: the code travels through your browser, which means it travels to whatever address the identity provider was told to send it to.

What PKCE adds

PKCE is defined in a public standards document, RFC 7636. It adds a verification step to the code exchange, and it works like a cloakroom ticket.

When you hand in your coat, the attendant gives you a ticket with a number on it. To get the coat back, you must present the matching ticket. Someone who saw the number written on the coat's label cannot collect the coat, because they do not hold the ticket.

In PKCE:

  • The client generates a random secret value called a code_verifier.
  • From that value it computes a second value, the code_challenge. The challenge is derived from the verifier but does not reveal it, in the same way a fingerprint does not let you reconstruct a person.
  • The challenge goes along with the initial authorization request.
  • Later, when the client exchanges the authorization code for tokens, it presents the original verifier.
  • The authorization server checks that the verifier matches the challenge it stored alongside the code.

If someone intercepts the authorization code but does not have the matching verifier, they should not be able to redeem it. That is the whole purpose of PKCE.

The gap

Here is the sentence that matters most in this section: PKCE does not decide whether the requested redirect destination is trustworthy. The authorization server has to enforce that separately by validating the redirect_uri.

These controls solve different problems, and both need to work correctly. PKCE answers "does the person redeeming this code hold the matching ticket?". Redirect URI validation answers "is this the right place to send the code at all?". A system can answer the first question perfectly and still fail the second.

2. Where the problem starts

Consider what happens when an attacker can influence the redirect URI in an authorization request.

An attacker can generate their own PKCE verifier and challenge before creating the request. This is the part beginners often miss. The attacker does not need to steal the victim's verifier, because the attacker is not trying to redeem the victim's code with the victim's ticket. The attacker started the request themselves and supplied the challenge that matches their own verifier.

So the sequence is:

  1. The attacker builds an authorization request, with their own verifier and challenge, and with a redirect URI pointing at a destination they control.
  2. The victim is persuaded to open that request and sign in. Their login is completely genuine.
  3. The identity provider, if it accepts the unauthorised redirect destination, sends the authorization code to the attacker's destination.
  4. The attacker already knows the verifier, because they generated it. If the remaining checks permit the exchange, they may be able to redeem the code.
Figure 2: An illustrative attack flow. The identity provider accepts an untrusted redirect destination, potentially exposing the authorization code. From the original on sanaullahamankorai.medium.com

Figure 2: An illustrative attack flow. The identity provider accepts an untrusted redirect destination, potentially exposing the authorization code.

The diagram illustrates an attack flow in which the identity provider accepts an untrusted redirect destination, potentially exposing the authorization code. Nothing about the victim's credentials is abused. Their password and one-time password can be correct, and the identity provider can authenticate them successfully. The failure occurs when the authorization server sends the authorization response to a destination that should not have been allowed.

This is why an OAuth implementation can use PKCE correctly and still have a serious authorization-flow vulnerability. The lock on the cloakroom door is fine; the attendant is handing the coat to the wrong person because the address on the ticket was never checked.

3. Why redirect URI validation matters

OAuth clients register redirect URIs with the identity provider. In plain terms, the client hands the identity provider a list of approved return addresses in advance, and during authorization the requested redirect URI must be validated against that registered configuration and the applicable protocol requirements.

Problems can arise when validation rules are too broad. Two common shapes:

  • Unsafe wildcard configurations. A wildcard is a rule that matches many addresses at once, for example "anything under this domain". It is convenient, and it is also a wide door.
  • Matching logic that accepts destinations outside the intended trust boundary. The rule may look strict but still let through addresses the client never meant to approve.

A team might believe that allowing a broad range of subdomains is convenient. But if an attacker can control one of those subdomains, or otherwise make an unauthorised destination satisfy the validation rule, the configuration may expose the authorization response.

One caution: the presence of a wildcard does not automatically make an implementation vulnerable. The actual risk depends on the matching rules, which destinations are trusted, and whether an attacker can control or exploit an accepted destination. A wildcard over domains nobody else can register is very different from a wildcard over a shared hosting space.

The key question is simple:

Can an authorization request direct the response to a destination that the client and identity provider should not trust?

If the answer is yes, the flow needs further investigation.

4. A simple example of the validation principle

The following Python example illustrates the basic idea of an explicit redirect URI allowlist. It is a teaching example, not a replacement for the identity provider's built-in validation.

Python
REGISTERED_REDIRECT_URIS = {    "https://app.example.test/oauth/callback"}

Line by line:

  • REGISTERED_REDIRECT_URIS is a name for a collection. The capitals are a convention meaning "this is a fixed list, not something that changes while the program runs".
  • = assigns the collection to that name.
  • The curly braces { ... } create a set, which is a collection that holds distinct items and can answer "is this item in here?" very quickly.
  • "https://app.example.test/oauth/callback" is the single approved return address. The .test ending is a reserved domain used in examples, so it cannot collide with a real website.
Python
def is_allowed_redirect_uri(redirect_uri: str) -> bool:    return redirect_uri in REGISTERED_REDIRECT_URIS

Line by line:

  • def starts the definition of a function, a named block of code you can call later.
  • is_allowed_redirect_uri is the function's name, chosen to read like a question.
  • redirect_uri: str is the input. The : str is a hint that the input should be text (a string).
  • -> bool is a hint that the function returns a true/false value.
  • return hands back the result.
  • redirect_uri in REGISTERED_REDIRECT_URIS asks whether the supplied address is exactly one of the approved ones. The answer is True or False.

The point of the example is the word explicit. The list is written out, and anything not on it is refused. There is no pattern matching, no wildcard, and no room for an address that merely looks similar.

In a real implementation, redirect URI validation should follow the applicable OAuth/OIDC requirements and the identity provider's supported configuration. Teams should not replace built-in validation with an improvised check without reviewing the protocol requirements. The broader principle is that authorization responses should only be sent to destinations that have been explicitly approved for the requesting client.

5. What about permissive CORS?

Redirect URI validation is not the only control worth reviewing, and this section explains a related one that is easy to confuse with it.

CORS (Cross-Origin Resource Sharing) is a browser rule about reading. A web page loaded from one site (one origin) is normally not allowed to read responses from a different site. CORS is the mechanism by which a server can say "actually, this other site is allowed to read my responses". It exists to stop a malicious page from quietly reading your data from another site you are logged in to.

If an identity provider's token endpoint has an overly permissive CORS policy, that can introduce additional risk for browser-based clients. For example, a policy that reflects arbitrary origins may allow websites that should not be trusted to read certain responses, depending on the endpoint's configuration and the browser's security rules. "Reflects" means the server copies whatever origin the requester claims and echoes it back as approved, which effectively approves everyone.

Two cautions follow:

  • CORS should be assessed separately from redirect URI validation.
  • A permissive CORS policy does not, by itself, prove account takeover, and it is not always necessary for an attacker to redeem a code outside the browser.

The impact depends on the complete flow, including the endpoint's requirements, browser behaviour, token handling, and client configuration. For that reason, it is better to document CORS as a separate finding or contributing weakness when the evidence supports it, rather than treating it as the root cause of every OAuth redirect vulnerability.

6. Short-lived authorization codes are not a complete fix

Authorization codes are designed to expire quickly and be used only once. Both controls reduce the opportunity for an attacker to reuse an intercepted code. Think of a paper ticket that is valid for two minutes and is taken away at the door: there is little time to copy it, and a copy will not work twice.

But they do not fix an unsafe redirect URI configuration. If a code reaches an untrusted destination and an attacker has the matching PKCE verifier, an automated exchange may be possible within the code's validity period, subject to the server's other checks. An automated exchange may be possible within the code's validity period.

Short expiration times and single-use enforcement are useful layers of defence. They should not be treated as substitutes for validating the redirect URI.

7. What the secure flow should look like

The authorization server should reject an authorization request when its redirect URI is not permitted for the requesting client. That decision must happen before the server issues an authorization response. An unapproved destination should not receive an authorization code at all.

PKCE should remain enabled. The goal is to combine it with proper redirect URI validation, appropriate token endpoint protections, and secure client configuration. A useful review should cover the entire authorization flow, not just whether a particular security feature is switched on.

8. What I would check during an OAuth assessment

When assessing an OAuth/OIDC deployment, I would review the following areas:

  • Registered redirect URIs: Remove unused entries and avoid unnecessarily broad matching rules.
  • Redirect validation: Confirm that unauthorized destinations are rejected and that validation follows the relevant protocol requirements.
  • PKCE enforcement: Confirm that the authorization server requires and verifies the correct code_verifier, using S256 where appropriate.
  • Authorization code handling: Check that codes are short-lived, bound to the appropriate client and redirect URI, and accepted only once.
  • CORS policy: Verify that only the necessary origins are allowed and that arbitrary origins are not reflected without justification.
  • Token scope and audience: Ensure that tokens grant only the intended permissions and are accepted only by their intended resource servers.
  • Impact verification: In an authorized test environment, determine whether the weakness exposes an authorization code, allows token issuance, or provides access to protected resources. These are distinct stages and should be reported accurately.

A few of those terms deserve a plain definition. Scope is the list of things a token is allowed to do, like a key card that opens the gym but not the safe. Audience is who the token is meant for; a token issued for one service should be refused by another. S256 is the specific hashing method PKCE uses to derive the challenge from the verifier, and it is the method you want.

This last point is especially important. Observing a suspicious redirect is not the same as demonstrating token theft, and obtaining a token is not automatically proof of access to every part of an account. Good security reporting separates what was observed from what was demonstrated.

The takeaway

The lesson from this assessment is not that PKCE is ineffective. It is that PKCE was never designed to replace redirect URI validation.

PKCE helps ensure that the party redeeming an authorization code possesses the corresponding verifier. Redirect URI validation helps ensure that the authorization response goes to an approved destination. Both controls are necessary for a secure authorization flow.

If you maintain an OAuth/OIDC deployment, do not stop your review after confirming that PKCE is enabled. Check the redirect URI rules, inspect the token endpoint's configuration, and verify what happens when an authorization request contains an unapproved destination. Security comes from the controls working together, not from the presence of any single feature.

Glossary

  • API (Application Programming Interface): an agreed way for one piece of software to ask another to do something and get a response back.
  • Audience (token audience): the service a token is intended for; other services should refuse it.
  • Authorization code: a short-lived string the identity provider hands back after login, which the client exchanges for tokens.
  • Authorization code flow: the standard OAuth pattern where the user logs in at the identity provider and the client receives a code, then swaps it for tokens.
  • Authorization request: the request the client sends to the identity provider to start the login, including where to send the user back.
  • Authorization response: what the identity provider sends back after login, carrying the authorization code.
  • Authorization server: the part of the identity provider that issues codes and tokens and checks the rules.
  • Client application: the website or app the user is trying to sign in to.
  • Code challenge: a value derived from the PKCE verifier and sent with the authorization request.
  • Code verifier: the random secret the client generates for PKCE and presents when exchanging the code.
  • CORS (Cross-Origin Resource Sharing): a browser rule, configurable by servers, that decides whether a page from one origin may read responses from another.
  • Identity provider: the trusted service that logs the user in and vouches for their identity.
  • Keycloak: an open-source identity and access management product, used here to build the banking identity platform.
  • OAuth 2.0: a standard that lets an application obtain limited access to protected resources without collecting the user's password.
  • OIDC (OpenID Connect): an identity layer built on OAuth 2.0 that lets applications authenticate users and receive identity information.
  • One-time password: a password valid for a single use, often generated by an app or sent by message.
  • Origin: the combination of scheme, host and port that a browser uses to decide whether two pages are the same site for security purposes.
  • PKCE: a security extension to OAuth, defined in RFC 7636, that ties a code exchange to a secret the client generated.
  • Redirect URI: the address the identity provider sends the user back to after login, carrying the authorization code.
  • Resource server: the system that holds the protected data and accepts tokens to grant access.
  • RFC 7636: the published standard that defines PKCE.
  • S256: the hashing method PKCE uses to derive the code challenge from the code verifier.
  • Scope: the set of permissions a token carries.
  • Set (in Python): a collection of distinct items that can be checked for membership quickly.
  • Token: a string that acts as a temporary pass granting access to protected resources.
  • Token endpoint: the server address where a client exchanges an authorization code for tokens.
  • Wildcard: a matching rule that covers many addresses at once, for example everything under a domain.

More by Sanaullah Aman Korai

View all

3 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

OAuth and single sign-on flaws

The lesson behind this report.

Mistakes in OAuth, OpenID Connect, SAML or token handling that leak codes and tokens or link an attacker's identity to a victim's account.