Implementing OAuth 2.0 (Part 2): Authorization Code + PKCE End to End
Build the modern OAuth authorization code flow correctly: PKCE generation, state, redirects, callbacks, token exchange, errors and server-side implementation patterns.

Part 1 established the model. Now we will walk through the interactive OAuth flow you are most likely to implement in a modern application: Authorization Code with PKCE.
The protocol is easier to reason about when you stop seeing it as one redirect and instead see four separate security events:
1. Client creates authorization transaction
2. Browser visits authorization server
3. Authorization server redirects browser back with a code
4. Client exchanges that code for tokens
Each event has data that must remain bound to the same transaction. Most serious implementation bugs happen when that binding is weak.
Our example application
Assume:
Client: https://app.example.com
Callback: https://app.example.com/oauth/callback
Authorization: https://identity.example.com/authorize
Token endpoint:https://identity.example.com/token
Client ID: web-app-123
The client wants:
scope=openid profile invoices.read
openid means this example is also using OpenID Connect for login. The OAuth mechanics are still the same authorization-code flow.
Step 1: create a transaction before redirecting anywhere
When the user chooses “Sign in,” create the values needed to bind the eventual callback to this browser session.
At minimum, a typical implementation will have:
state
code_verifier
code_challenge
An OIDC transaction will normally also have:
nonce
Do not create these as convenient constants in configuration.
They belong to one authorization transaction.
Generate a PKCE verifier
The verifier must be high entropy. Use a cryptographically secure random-number generator, not Math.random() or a timestamp.
Conceptually:
const verifier = base64url(secureRandomBytes(32));
Then derive the S256 challenge:
const challenge = base64url(sha256(verifier));
The verifier remains private to the client transaction. The challenge goes to the authorization server.
Generate state
Create an unpredictable state value and bind it to the user’s transaction:
const state = base64url(secureRandomBytes(32));
A server-side application might store transaction state in an encrypted/signed cookie or server-side session keyed by a short-lived correlation cookie.
For example, conceptually:
transaction[state] = {
codeVerifier: "...",
nonce: "...",
returnUrl: "/account"
}
Expire authorization transactions quickly and make them single-use.
Do not put an arbitrary return URL into state
A common convenience implementation does this:
state=/account
Then another developer expands it:
state=https://somewhere.example/
Now the callback trusts a browser-controlled value as a redirect destination.
state can carry application state, but integrity and redirect safety still matter. A cleaner pattern is to generate a random transaction identifier and keep the return destination in trusted transaction storage.
After successful authentication, validate the stored return path against your application’s allowed destinations.
Step 2: build the authorization request
The browser is redirected to something like:
https://identity.example.com/authorize
?response_type=code
&client_id=web-app-123
&redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth%2Fcallback
&scope=openid%20profile%20invoices.read
&state=STATE_VALUE
&code_challenge=PKCE_CHALLENGE
&code_challenge_method=S256
&nonce=OIDC_NONCE
Do not hand-concatenate this URL if your platform library can construct it safely.
The authorization server should know the client’s permitted redirect URIs from registration. The request is not permission for the client to choose any destination it likes.
Step 3: the authorization server handles the user interaction
The authorization server owns the authentication experience.
It may:
- reuse an existing login session;
- ask for credentials;
- require MFA;
- apply enterprise access policy;
- ask the user to approve requested scopes;
- deny the request.
Your client should not need the user’s credentials for the authorization server.
That separation is one of the central benefits of the architecture.
Step 4: the browser returns to the callback
On success:
GET /oauth/callback?code=AUTHORIZATION_CODE&state=STATE_VALUE
Do not treat arrival at this endpoint as successful login yet.
You still have work to do.
Validate the transaction
Retrieve the short-lived transaction associated with the callback and verify the expected correlation values.
Reject:
- unknown state;
- expired state;
- already-used state;
- a callback that cannot be bound to the browser transaction that initiated authorization.
Once consumed, invalidate the transaction so replaying the callback does not restart the same exchange.
Treat the authorization code as temporary protocol data
Do not log it casually:
OAuth callback received code=abc123...
Authorization codes are short-lived and single-use, but they are still sensitive values. Query-string logging at proxies, application servers and observability platforms can create unnecessary exposure.
Redact OAuth parameters from logs where practical.
Step 5: exchange the code at the token endpoint
The browser should not need to manually orchestrate this exchange for a server-side web client.
The client sends a back-channel request:
POST /token HTTP/1.1
Host: identity.example.com
Content-Type: application/x-www-form-urlencoded
client_id=web-app-123&
grant_type=authorization_code&
code=AUTHORIZATION_CODE&
redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth%2Fcallback&
code_verifier=ORIGINAL_CODE_VERIFIER
A confidential client will also authenticate itself using the client-authentication mechanism agreed with the authorization server. That may be a secret-based mechanism or, in higher-assurance deployments, an asymmetric method such as private_key_jwt or mutual TLS.
The important distinction is that client authentication and PKCE solve different problems. A confidential client does not become exempt from modern PKCE guidance merely because it has a client secret.
What the authorization server checks
At token exchange, a correct server validates more than “does this code exist?”
It binds the code to the original authorization transaction, including relevant properties such as:
client
redirect URI
PKCE challenge
requested/granted authorization
expiry
single-use state
It verifies that:
BASE64URL(SHA256(code_verifier)) == stored_code_challenge
If the verifier is wrong, the exchange fails.
If the code has already been redeemed, it fails.
If the code belongs to a different client, it fails.
This is why an authorization code should not be modeled as a random database row that any authenticated client can redeem.
The token response
A successful response may look conceptually like:
{
"access_token": "...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "...",
"scope": "openid profile invoices.read",
"id_token": "..."
}
Do not assume every field is always present.
An OAuth-only request will not produce an OIDC ID Token. A provider may not issue refresh tokens under every policy. The granted scopes can differ from those requested.
Your client library should parse the protocol response and expose the values according to the provider’s metadata and specifications.
Step 6: validate OpenID Connect before creating a login session
If this is an OIDC login, the ID Token must be validated according to OIDC rules before the application treats the user as authenticated.
That includes checks such as:
signature
issuer (iss)
audience (aud)
expiry (exp)
nonce, when used
other flow/provider-specific requirements
Do not merely Base64-decode the JWT and trust the JSON because it contains an email address.
JWT encoding is not proof of authenticity.
A mature OIDC library should perform protocol validation using the provider’s discovery metadata and published signing keys.
Step 7: create your own application session
For a conventional server-rendered web application, you usually do not want to send the OAuth access token to the browser merely because the browser initiated the login.
Instead:
OAuth/OIDC completes on server
↓
server validates tokens
↓
server stores required token material securely
↓
server creates application session
↓
browser receives hardened session cookie
For example:
Set-Cookie: __Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax
The exact SameSite policy depends on your architecture, but the general principle is valuable: browser JavaScript does not need access to a server-side session cookie when the application can operate without it.
Error callbacks are part of the protocol
Users deny consent. Sessions expire. Policies block requests. Authorization servers return errors.
A callback can therefore contain:
error=access_denied
state=...
or other protocol-defined error fields.
Validate the transaction correlation even on error responses before acting on them.
Do not display raw provider error descriptions directly inside HTML without safe encoding. Protocol errors are input from another system and should be handled like input.
Give the user a useful outcome:
You cancelled the authorization request. No access was granted.
is much better than:
OAuth error: access_denied
Avoid callback pages that load unnecessary third parties
The callback URL temporarily contains sensitive authorization protocol parameters.
Keep that route boring.
It does not need marketing analytics, ad scripts, social widgets or a dozen unrelated third-party resources before the authorization code has been processed.
A good callback handler performs the protocol work, removes sensitive parameters from the browser’s visible URL through an appropriate redirect, then sends the user to the intended application page.
For example:
/oauth/callback?code=...&state=...
↓ validate/exchange
/account
This also prevents users from bookmarking or refreshing a consumed authorization-code URL.
Do not leak callback query strings into telemetry
OAuth values can end up in more places than application logs:
CDN access logs
reverse-proxy logs
APM transaction names
browser analytics
session replay products
error tracking breadcrumbs
support screenshots
Review observability around authentication routes deliberately.
You still need useful logs — provider, correlation ID, outcome, duration and sanitized error code are valuable — but you rarely need raw tokens, authorization codes or PKCE verifiers.
A server-side implementation shape
The exact APIs vary by framework, but the responsibilities are stable.
Login endpoint
GET /login
1. create transaction ID/state
2. create PKCE verifier
3. derive S256 challenge
4. create OIDC nonce if required
5. store short-lived transaction
6. redirect to authorization endpoint
Callback endpoint
GET /oauth/callback
1. locate transaction
2. validate state/correlation
3. reject errors or invalid transaction
4. exchange code + verifier at token endpoint
5. validate OIDC response if applicable
6. create application session
7. destroy transaction
8. redirect to validated local return URL
This is the shape your OAuth library should be implementing for you, even if most of it is hidden behind middleware.
Why libraries are still the right answer
After reading the flow in detail, it can be tempting to think: “That is not much code.”
The happy path is not much code.
Production support is where the complexity lives:
key rotation
clock skew
issuer validation
multiple providers
metadata caching
nonce validation
refresh token lifecycle
callback replay
logout
error handling
mix-up protection
DPoP/mTLS profiles
provider quirks
Understanding the mechanics lets you configure and audit a library correctly. It should not encourage you to replace a mature protocol implementation with home-grown string manipulation.
Native applications need different redirect handling
Installed applications cannot protect a conventional client secret, so they are public clients and PKCE is essential.
Their redirect options differ from web apps. Depending on platform and ecosystem, native apps may use claimed HTTPS URLs, loopback redirects or private-use URI schemes under the rules defined for native OAuth applications.
Do not copy a desktop app’s localhost callback pattern into a production web client, and do not assume a custom URI scheme has the same ownership properties as an HTTPS origin.
Use the platform’s OAuth library and the provider’s supported native-app profile.
Browser-based applications require an architectural decision
A pure SPA can perform Authorization Code + PKCE without pretending to possess a client secret.
But successful authorization leaves you with a harder question:
where should the access and refresh tokens live?
That is not a minor storage implementation detail. It changes what an XSS vulnerability or compromised dependency can steal.
A BFF architecture keeps tokens on a backend and exposes a session to the browser instead. A direct SPA architecture lets the browser call the API with OAuth credentials.
Both require deliberate security design. Part 4 will compare them using the current IETF browser-based-app guidance.
Common failures to test deliberately
Before shipping, test more than a successful sign-in:
- callback with missing state;
- callback with incorrect state;
- callback after transaction expiry;
- replay of a previously successful callback;
- wrong PKCE verifier;
- authorization error such as
access_denied; - code exchange timeout;
- invalid or expired ID Token;
- issuer/audience mismatch;
- provider key rotation;
- user opening login in multiple tabs;
- return URL tampering;
- logout followed by stale browser navigation.
Authentication code that only works when everything is healthy is not production-ready authentication code.
A note on multiple authorization servers
If one client can interact with more than one authorization server, additional mix-up attack protections are required.
Modern OAuth security guidance recommends mechanisms that let the client reliably identify the issuer associated with the authorization response, such as the authorization-response iss parameter where supported, OIDC issuer information, or other defined countermeasures.
Do not accept a callback and then choose the token endpoint based on attacker-controlled callback data.
The client needs to know which authorization server began the transaction and ensure the response belongs to it.
Production checklist for Authorization Code + PKCE
Before moving on, verify that your implementation has all of these properties:
- Authorization Code flow, not Implicit, for new interactive clients;
- PKCE enabled with
S256; - cryptographically random, transaction-specific verifier;
- exact registered redirect URIs;
- no open redirector in the callback chain;
- state/transaction correlation validated as required by your profile/library;
- OIDC nonce generated and validated where applicable;
- authorization codes treated as sensitive, short-lived and single-use;
- token exchange performed only over TLS;
- confidential-client authentication kept server-side;
- ID Tokens fully validated before login is established;
- application return destinations validated rather than trusted from browser input;
- tokens/codes/verifiers redacted from logs and analytics;
- consumed callback URLs redirected to clean application URLs;
- error paths and replay scenarios tested.
What Part 3 adds
At the end of this flow you possess tokens. That is where a second class of mistakes begins.
Part 3 covers access-token validation, JWTs versus opaque tokens, audiences, scopes, refresh-token rotation and resource-server authorization — including why successfully verifying a JWT signature is nowhere near enough to authorize a request.
