
OAuth 2.1 and OpenID Connect Explained for Developers (2026): Flows, Tokens, PKCE, and Security
OAuth is everywhere on the modern web. It is behind every “Sign in with Google” button, every app that reads your calendar, and every API that hands out access tokens. It is also one of the most misunderstood pieces of web security. Developers mix up OAuth and OpenID Connect, store tokens in the wrong place, and skip the checks that make the whole thing safe.
The good news is that the rules got simpler. OAuth 2.0 grew a pile of extensions and security advice over twelve years. OAuth 2.1 gathers the parts that survived into one document and removes the flows that proved unsafe. If you follow OAuth 2.1 and a few companion standards, you avoid most of the classic mistakes.
This guide explains the whole picture in plain terms. You will learn what OAuth and OpenID Connect each do, how the authorization code flow with PKCE works step by step, and how to validate an ID token correctly. You will also learn where to keep tokens in a single-page app, and which attacks to defend against.
I tested the code. The PKCE helpers match the official test vector from RFC 7636. The ID token validator passed 10 checks against tokens I signed with a locally generated RSA key, including forged, expired, and tampered tokens. I did not test against a live identity provider. The standards status comes from the IETF Datatracker and the RFC Editor, which I checked on November 26, 2026.
This article is part of my security series. It pairs with my guides to passkeys and 2FA, secrets management, and MCP servers, which use OAuth for authorization.
Table of Contents
- The Short Answer
- OAuth, OpenID Connect, and SAML
- The Vocabulary
- What Changed in OAuth 2.1
- The Authorization Code Flow with PKCE
- Code: PKCE, State, and Nonce
- OpenID Connect and the ID Token
- Code: Validating an ID Token
- Access Tokens and Resource Servers
- Refresh Tokens
- Choosing a Flow for Your Client
- Single-Page Apps and the BFF Pattern
- Stronger Tokens: DPoP, mTLS, and PAR
- Attacks and Defenses
- Libraries and Providers
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
Use the authorization code flow with PKCE for every app that has a user. Use OpenID Connect on top of it when you need to know who the user is. Never build your own authorization server unless that is your product.
| You are building… | Use this |
|---|---|
| A server-rendered web app | Authorization code with PKCE, a confidential client, and a session cookie |
| A single-page app (React, Vue, Svelte) | A backend for frontend (BFF) that holds the tokens, per RFC 10017 |
| A mobile or desktop app | Authorization code with PKCE in the system browser, per RFC 8252 |
| A service calling another service | The client credentials grant |
| A TV, CLI, or device without a keyboard | The device authorization grant (RFC 8628) |
| “Sign in with…” for your users | OpenID Connect, and validate the ID token |
Five rules prevent most real-world OAuth bugs.
- Always use PKCE: RFC 9700 requires it for public clients and recommends it for every other client.
- Match redirect URIs exactly: No wildcards, no prefix matching, no open redirects.
- Never use the implicit or password grants: OAuth 2.1 removes both.
- Validate every token you accept: Check the signature, issuer, audience, expiry, and nonce.
- Keep tokens out of browser JavaScript when you can: A BFF keeps them on the server.
2. OAuth, OpenID Connect, and SAML
These three get mixed up constantly, so it helps to separate them first.
OAuth is about authorization. It lets an app get limited access to an API on a user’s behalf. The app receives an access token that says “this bearer may read this user’s calendar.” The token does not, by itself, tell the app who the user is.
OpenID Connect (OIDC) is about authentication. It is a thin identity layer on top of OAuth. It adds an ID token, which is a signed statement from the provider that says “this user, with this ID, signed in at this time, for this app.” When you build “Sign in with Google,” you are using OpenID Connect.
SAML is the older enterprise option. It also handles single sign-on, using XML assertions instead of JSON tokens. Many companies still use it for workforce sign-in. For new consumer apps and APIs, OIDC is the usual choice.
The common mistake is using an OAuth access token as proof of identity. An access token is meant for an API, not for your app. Your app cannot always read it, and it may have been issued to a different app. Use the ID token for identity, and the access token only to call APIs.
3. The Vocabulary
OAuth has its own terms. These are the ones you need.
- Resource owner: The user who owns the data and grants access.
- Client: Your application, which wants access.
- Authorization server: The service that authenticates the user and issues tokens. In OIDC, it is called the OpenID Provider.
- Resource server: The API that accepts access tokens.
- Access token: A short-lived credential that the client sends to the resource server.
- Refresh token: A longer-lived credential that gets new access tokens without asking the user again.
- ID token: An OIDC token that describes the signed-in user. It is always a JWT.
- Scope: A named permission, such as
read:calendaroropenid email. - Redirect URI: Where the authorization server sends the user back after sign-in.
- Confidential client: A client that can keep a secret, such as a server-side web app.
- Public client: A client that cannot keep a secret, such as a mobile app or a browser app.
The difference between confidential and public clients matters a lot. Anything shipped to a user’s device can be unpacked, so a mobile app’s “client secret” is not secret. Public clients rely on PKCE instead.
4. What Changed in OAuth 2.1
OAuth 2.1 is not a new protocol. It is OAuth 2.0 with the lessons of the last decade applied. It replaces RFC 6749 and RFC 6750, and it folds in PKCE, the native apps guidance, and the security best practices.
Its status in late 2026
OAuth 2.1 is still an Internet-Draft. The latest revision is draft 17, dated October 31, 2026. It has no RFC number yet, and its authors are Dick Hardt, Aaron Parecki, and Torsten Lodderstedt. The content has been stable for a long time, and major providers already follow it.
You do not need to wait for the RFC. The rules in OAuth 2.1 are already required by RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025. Following OAuth 2.1 today means following current best practice.
The changes
| Change | Why |
|---|---|
| PKCE required for the authorization code flow | Stops stolen or injected authorization codes from being redeemed |
| Implicit grant removed | It returned tokens in the URL, where they leaked into logs and history |
| Resource owner password grant removed | It taught users to type passwords into third-party apps |
| Exact string matching for redirect URIs | Wildcard matching let attackers steal codes through crafted URLs |
| Bearer tokens not allowed in query strings | URLs end up in logs, proxies, and referrer headers |
| Refresh tokens for public clients restricted | They must be sender-constrained or rotate on every use |
OAuth 2.1 allows one narrow exception to PKCE. A confidential client that uses OpenID Connect may rely on the nonce instead. Using PKCE anyway costs nothing, so most guides, including this one, recommend it everywhere.
5. The Authorization Code Flow with PKCE
This is the flow you will use for nearly every user-facing app. The diagram shows the whole exchange, and the steps below explain each arrow.
Browser Client app Authorization server API
| | | |
| click "Sign in" | | |
|-------------------->| create verifier, state, nonce| |
|<--------------------| redirect with code_challenge | |
|---------------------------------------------------->| user signs in |
|<----------------------------------------------------| redirect: code, state |
|-------------------->| check state | |
| |--- code + code_verifier ---->| hash verifier, compare|
| |<-- access, refresh, ID token-| |
| | validate ID token | |
| |--- Authorization: Bearer access token -------------->|
| |<-------------------------------------------- data ---|
The browser only ever carries the short-lived code. The tokens travel directly between the client and the servers.
Step 1: the client prepares
The client creates three random values.
code_verifier: A secret random string, kept by the client.code_challenge: The base64url-encoded SHA-256 hash of the verifier. This one is sent to the server.state: A random value that ties the response to this browser session.
An OIDC client also creates a nonce, which will come back inside the ID token.
Step 2: the browser goes to the authorization server
The client redirects the user to the authorization endpoint.
GET /authorize?response_type=code
&client_id=my-client
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&scope=openid%20email%20read%3Ainvoices
&state=af0ifjsldkj
&nonce=n-0S6_WzA2Mj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256 HTTP/1.1
Host: id.example.com
The user signs in and approves the requested scopes. The client never sees the user’s password.
Step 3: the server redirects back with a code
HTTP/1.1 302 Found
Location: https://app.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=af0ifjsldkj&iss=https%3A%2F%2Fid.example.com
The client checks that state matches the value it stored. If the client talks to more than one authorization server, it also checks the iss parameter. RFC 9207 defines that parameter to stop mix-up attacks.
Step 4: the client exchanges the code for tokens
This call goes directly from the client to the token endpoint, not through the browser.
curl -X POST https://id.example.com/token \
-d grant_type=authorization_code \
-d code=SplxlOBeZQQYbYS6WxSbIA \
-d redirect_uri=https://app.example.com/callback \
-d client_id=my-client \
-d code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
The server hashes the code_verifier and compares it with the code_challenge from step 2. Only the client that started the flow knows the verifier. An attacker who intercepted the code cannot redeem it.
A confidential client also authenticates here. The simplest method is a client secret. A stronger one is private_key_jwt, where the client signs a short assertion with its private key, so no shared secret ever crosses the network.
Step 5: the server returns tokens
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 600,
"refresh_token": "8xLOxBtZp8",
"id_token": "eyJhbGciOiJSUzI1NiIs...",
"scope": "openid email read:invoices"
}
The client validates the ID token, creates its own session, and uses the access token to call the API.
6. Code: PKCE, State, and Nonce
The helpers below use only Node’s built-in Web Crypto API, which also exists in browsers, Deno, Bun, and Cloudflare Workers. They need no dependencies.
// oidc.mjs (part 1): PKCE helpers using only built-in Web Crypto.
const enc = new TextEncoder();
export function base64url(bytes) {
return Buffer.from(bytes).toString("base64url");
}
// PKCE (RFC 7636): a random verifier and its S256 challenge.
export function createVerifier() {
return base64url(crypto.getRandomValues(new Uint8Array(32))); // 43 characters
}
export async function challengeFor(verifier) {
const digest = await crypto.subtle.digest("SHA-256", enc.encode(verifier));
return base64url(new Uint8Array(digest));
}
// Random values for state and nonce.
export function randomToken() {
return base64url(crypto.getRandomValues(new Uint8Array(32)));
}
In a browser, replace Buffer with the small function below, because Buffer is a Node API. I checked it against Node’s own encoder on 2,000 random inputs, and it also reproduces the RFC 7636 test vector.
// Browser-safe replacement for base64url() above.
export function base64url(bytes) {
let s = "";
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
How to use them
Create the verifier, state, and nonce before the redirect, and store them where only this browser session can read them. On a server, that is the user’s session. The values must survive the round trip to the authorization server.
const verifier = createVerifier();
const state = randomToken();
const nonce = randomToken();
session.oauth = { verifier, state, nonce }; // server-side session store
const url = new URL("https://id.example.com/authorize");
url.search = new URLSearchParams({
response_type: "code",
client_id: "my-client",
redirect_uri: "https://app.example.com/callback",
scope: "openid email",
state,
nonce,
code_challenge: await challengeFor(verifier),
code_challenge_method: "S256",
});
// redirect the browser to url.toString()
On the callback, compare state first. Then send the stored verifier to the token endpoint, and delete all three values so they cannot be reused.
PKCE test results
| Check | Result |
|---|---|
| RFC 7636 Appendix B test vector matches | Pass |
| Verifier length is between 43 and 128 characters | Pass |
| Verifier uses only unreserved characters | Pass |
| Two state values are never equal | Pass |
The test vector is the one that every PKCE implementation must match. The verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk must produce the challenge E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, and mine does.
Always use the S256 method. The plain method sends the verifier itself as the challenge, so it protects nothing if the authorization request leaks. RFC 9700 names S256 as the only method it considers safe.
7. OpenID Connect and the ID Token
An ID token is a JSON Web Token (JWT). It has three base64url parts separated by dots: a header, a payload of claims, and a signature.
A decoded payload looks like this.
{
"iss": "https://id.example.com",
"sub": "248289761001",
"aud": "my-client",
"exp": 1795689600,
"iat": 1795689000,
"nonce": "n-0S6_WzA2Mj",
"auth_time": 1795688990,
"email": "jane@example.com",
"email_verified": true
}
The claims that matter
iss: The issuer, which must equal your provider’s exact issuer URL.sub: The user’s stable ID at this provider. Useissplussubas the user key in your database.aud: The audience, which must contain your client ID.expandiat: Expiry and issue time, in seconds since 1970.nonce: The value you sent in the authorization request.auth_time,acr,amr: When and how the user authenticated. Check these for step-up flows.
Do not use email as the user key. Emails change, and some providers let users set an email they do not control. Use it as contact data only, and trust it only when email_verified is true.
Discovery and keys
Every OIDC provider publishes a discovery document at /.well-known/openid-configuration. It lists the endpoints, the supported features, and the jwks_uri. That URI serves the provider’s public signing keys as a JSON Web Key Set.
Cache the key set, and refresh it when a token arrives with an unknown kid. Providers rotate keys, and a client that never refreshes will break on rotation day. Rate-limit the refresh, so a flood of tokens with random kid values cannot hammer the provider.
The UserInfo endpoint
The UserInfo endpoint returns profile claims when you call it with the access token. Use it when you need more data than the ID token carries. Its response is not always signed, so the ID token remains the proof of authentication.
8. Code: Validating an ID Token
OpenID Connect Core, section 3.1.3.7, lists the checks a client must make. Skipping any of them opens a real attack. The function below performs them in order.
This code is intentionally minimal. In production, use jose or openid-client. The example exists so you can see every required check, and notice when a library or middleware skips one.
// oidc.mjs (part 2): validate an ID token per OIDC Core 1.0, section 3.1.3.7.
// For production, prefer a maintained library such as jose or openid-client.
function decodePart(part) {
return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
}
export async function validateIdToken(
idToken,
{ jwks, issuer, clientId, nonce, now = Date.now() / 1000, skew = 60 },
) {
const parts = idToken.split(".");
if (parts.length !== 3) throw new Error("malformed token");
const [h, p, s] = parts;
const header = decodePart(h);
// 1. Pin the algorithm. Never trust "none" or whatever the header claims.
if (header.alg !== "RS256") throw new Error(`unexpected alg ${header.alg}`);
// 2. Find the signing key by its key id.
const jwk = jwks.keys.find((k) => k.kid === header.kid && k.kty === "RSA");
if (!jwk) throw new Error("unknown signing key");
const key = await crypto.subtle.importKey(
"jwk",
jwk,
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
false,
["verify"],
);
// 3. Verify the signature over "header.payload".
const ok = await crypto.subtle.verify(
"RSASSA-PKCS1-v1_5",
key,
Buffer.from(s, "base64url"),
enc.encode(`${h}.${p}`),
);
if (!ok) throw new Error("bad signature");
// 4. Check the claims.
const c = decodePart(p);
if (c.iss !== issuer) throw new Error("wrong issuer");
const aud = Array.isArray(c.aud) ? c.aud : [c.aud];
if (!aud.includes(clientId)) throw new Error("wrong audience");
if (aud.length > 1 && c.azp !== clientId) throw new Error("wrong azp");
if (typeof c.exp !== "number" || now > c.exp + skew)
throw new Error("expired");
if (typeof c.iat !== "number" || c.iat > now + skew)
throw new Error("issued in the future");
if (c.nonce !== nonce) throw new Error("nonce mismatch");
if (!c.sub) throw new Error("missing sub");
return c;
}
How to read this code
- The algorithm is pinned before anything else. The header is attacker-controlled. A validator that trusts
algcan be tricked into acceptingnone, or into using an RSA public key as an HMAC secret. - The key comes from the provider’s key set, never from the token itself. Some JWT headers can carry a key, and trusting it would let anyone sign tokens.
- The signature is checked before the claims are trusted. Reading claims first is fine for logging, but no decision may depend on them.
- The audience check handles arrays. When a token has several audiences, OIDC requires the
azpclaim to name your client. - A small clock skew is allowed. Sixty seconds is a common value, because servers rarely agree on the exact time.
Validator test results
I generated a 2048-bit RSA key pair, published the public half as a key set, and signed test tokens with the private half. Then I fed the validator good and bad tokens.
| Test | Expected result | Actual result |
|---|---|---|
| Valid token | Accepted | Accepted |
| Issuer from another domain | Rejected | wrong issuer |
| Token issued for another client | Rejected | wrong audience |
Two audiences and no azp |
Rejected | wrong azp |
| Expired one hour ago | Rejected | expired |
| Nonce from an older login | Rejected | nonce mismatch |
Header says alg: none, no signature |
Rejected | unexpected alg none |
Payload changed to sub: admin after signing |
Rejected | bad signature |
| Unknown key id | Rejected | unknown signing key |
| Header switched to HS256 | Rejected | unexpected alg HS256 |
All ten behaved as expected. The alg: none and HS256 cases are not theoretical. Both have broken real JWT libraries in the past.
Use a library in production. jose and openid-client handle key caching, more algorithms, and edge cases that this short example skips. The point of the example is to show what those libraries check for you, so you notice when a library or a hand-rolled middleware skips a step.
9. Access Tokens and Resource Servers
Your API is a resource server. It must check every access token it receives, on every request.
Two kinds of access token
- JWT access tokens: The API validates the signature locally, using the provider’s key set. RFC 9068 defines a standard profile for them. They are fast, but you cannot revoke one before it expires.
- Opaque tokens: Random strings with no readable content. The API asks the authorization server about each one through token introspection, defined in RFC 7662. Revocation takes effect at once, at the cost of a network call.
Short lifetimes make JWT access tokens safer. Five to fifteen minutes is common. A stolen token then expires quickly, and refresh tokens handle the rest.
What the API must check
- Signature or introspection result: The token is genuine and active.
- Issuer: It came from the authorization server you trust.
- Audience: It was issued for this API. RFC 9700 says access tokens should be restricted to a specific resource server, and that a server must refuse tokens meant for another one.
- Expiry: It has not expired.
- Scopes: It grants the permission this endpoint needs.
- Your own authorization rules: The token says who the caller is. Your code still decides whether that caller may touch this specific invoice.
Warning: A valid access token proves that the caller may perform some kind of action. It never proves that the caller may touch this specific record. A token with
read:invoicesdoes not mean the caller may read every invoice. Check object-level ownership in your own code on every request, because no token can do it for you.
This gap causes many real breaches. It tops the OWASP API Security Top 10 as broken object level authorization.
Resource indicators
When one authorization server protects several APIs, the client should say which one a token is for. RFC 8707 adds a resource parameter to the authorization and token requests. The server then issues a token whose audience is that single API. A token stolen from one API cannot be replayed against another.
The Model Context Protocol uses exactly this pattern. An MCP server acts as an OAuth resource server, and MCP clients send the resource parameter. MCP servers also publish OAuth Protected Resource Metadata, defined in RFC 9728, so clients can discover the right authorization server.
10. Refresh Tokens
A refresh token lets a client get new access tokens without sending the user through sign-in again. That makes it valuable to attackers, because a stolen refresh token can last for weeks.
The standards are strict here. RFC 9700 says refresh tokens for public clients must be sender-constrained or use rotation. RFC 10017 adds more rules for browser-based clients.
Rotation
With rotation, every use of a refresh token returns a new refresh token, and the old one stops working. If an attacker steals a token and uses it, the legitimate client’s next refresh fails. The authorization server sees an old token being reused, which signals theft, and it revokes the whole token family.
Lifetimes
RFC 10017 requires browser-based clients to have refresh tokens with either a maximum lifetime or an idle timeout. A rotated token must not extend the lifetime of the original token beyond its set expiry. That stops an attacker from keeping a stolen session alive forever.
Practical settings
| Setting | Typical value |
|---|---|
| Access token lifetime | 5 to 15 minutes |
| Refresh token idle timeout | 1 to 14 days, depending on risk |
| Refresh token absolute lifetime | 30 to 90 days for consumer apps |
| Rotation | On, for every public client |
| Revocation on account changes | Revoke the whole refresh token family on a password change, MFA reset, or account disable |
11. Choosing a Flow for Your Client
Server-rendered web apps
This is the easiest and safest case. The server is a confidential client. It runs the code flow with PKCE, stores tokens in its own database or session store, and gives the browser only an HttpOnly, Secure, SameSite session cookie. The browser never sees a token.
Mobile and desktop apps
RFC 8252 sets the rules. Open the authorization page in the system browser or an in-app browser tab, such as ASWebAuthenticationSession on Apple platforms or Custom Tabs on Android. Never use an embedded web view, because the app could read the user’s password from it.
For the redirect, prefer claimed HTTPS links, such as Universal Links or App Links. Custom URL schemes work, but another app can register the same scheme. PKCE protects the code even then, which is why it is mandatory. Desktop apps can also redirect to a loopback address with a random port.
Machine-to-machine
When no user is involved, use the client credentials grant. The service authenticates with its own credentials and receives a token for its own permissions. Prefer private_key_jwt or mutual TLS over long-lived shared secrets. In cloud environments, workload identity federation can remove stored secrets entirely, as my secrets management guide explains.
Devices without a browser
Smart TVs and command-line tools use the device authorization grant from RFC 8628. The device shows a short code, and the user approves it on a phone or laptop. Watch for phishing here, because attackers send victims real device codes and ask them to “verify” them.
12. Single-Page Apps and the BFF Pattern
Browser apps are the hardest case, and the advice changed recently. RFC 10017, “OAuth 2.0 for Browser-Based Applications,” was published in August 2026 as a Best Current Practice. Its authors are Aaron Parecki, Philippe De Ryck, and David Waite.
The three patterns
RFC 10017 describes three architectures.
- Backend for frontend (BFF): A small server-side component runs the OAuth flow and keeps the tokens. The browser talks to the BFF with a session cookie, and the BFF forwards API calls with the access token.
- Token-mediating backend: A backend runs the flow but hands the access token to the browser, which calls APIs directly.
- Browser-based OAuth client: The JavaScript app runs the whole flow and holds all tokens itself.
| Pattern | Tokens in the browser | Security ranking | Use it for |
|---|---|---|---|
| Backend for frontend | None | Strongest | Business apps, sensitive apps, personal data |
| Token-mediating backend | Access token only | Middle | Apps that must call APIs directly |
| Browser-based OAuth client | All tokens | Weakest | Low-risk apps with no backend |
The RFC strongly recommends the BFF for business applications, sensitive applications, and applications that handle personal data. In practice, that covers most apps.
Why the browser is a hard place for tokens
If an attacker runs JavaScript in your origin through an XSS bug, they can read anything your JavaScript can read. RFC 10017 is explicit about localStorage. It persists between reloads, it is shared across tabs, and it does nothing against malicious code running in the same origin.
Even in-memory storage does not fully help. An attacker with script access can start a fresh authorization flow silently in a hidden frame and receive brand-new tokens. That is why the BFF wins. With a BFF, there is no token in the browser to steal, and the session cookie is HttpOnly.
A minimal BFF
A BFF does not need to be big. It handles four routes.
/login: Starts the code flow with PKCE and redirects to the provider./callback: Exchanges the code, validates the ID token, and sets anHttpOnlysession cookie./api/*: Looks up the session’s access token, refreshes it if needed, and forwards the request./logout: Clears the session and calls the provider’s logout endpoint.
Protect the BFF against cross-site request forgery. A SameSite=Strict or Lax cookie helps. Requiring a custom header, such as X-Requested-With, on API calls adds a second layer, because cross-site forms cannot set custom headers.
Run the BFF on the same site as the frontend, for example at app.example.com/bff. Third-party cookies are increasingly blocked, so a BFF on a different site may lose its session cookie.
Logout
Signing out involves up to three sessions: your app’s session, the tokens it holds, and the user’s session at the provider. OpenID Connect defines three logout specifications for keeping them in step.
- RP-Initiated Logout: Your app redirects the user to the provider’s
end_session_endpoint, with the ID token as a hint. The provider ends its own session and sends the user back. - Back-Channel Logout: The provider calls your server directly with a signed logout token when the user signs out elsewhere. Your server then ends the matching session. This is the most reliable option, because no browser is involved.
- Front-Channel Logout: The provider loads your logout URL in hidden iframes. It depends on third-party cookies, so it fails more and more often in modern browsers.
A good logout does three things. It clears your own session, revokes the refresh token at the provider, and ends the provider session with RP-initiated logout. Add back-channel logout if users expect signing out in one app to sign them out everywhere.
13. Stronger Tokens: DPoP, mTLS, and PAR
A bearer token works for anyone who holds it, like cash. Sender-constrained tokens work only for the client they were issued to.
DPoP
DPoP, defined in RFC 9449, binds a token to a key pair that the client generates. Every request carries a short signed proof that includes the HTTP method, the URL, and a timestamp. A stolen token is useless without the private key. In browsers, the key can be a non-extractable Web Crypto key, which even XSS cannot export.
DPoP works for public clients, including mobile apps and SPAs. It is the main way to meet RFC 9700’s requirement for sender-constrained refresh tokens without rotation.
Mutual TLS
RFC 8705 binds tokens to a client’s TLS certificate. It is common in banking and other regulated APIs. It needs certificate management, so it suits server-to-server traffic more than consumer apps.
Pushed authorization requests
With PAR, defined in RFC 9126, the client sends the authorization parameters directly to the server first. It then redirects the browser with only a short reference. The parameters cannot be read or tampered with in the browser, and long requests no longer hit URL length limits.
FAPI 2.0
The FAPI 2.0 Security Profile from the OpenID Foundation combines these pieces for high-risk APIs. It requires PAR, PKCE, sender-constrained tokens, and strict client authentication. Open banking schemes in several countries build on it. Even if you are not a bank, it is a useful checklist.
14. Attacks and Defenses
| Attack | How it works | Defense |
|---|---|---|
| Authorization code interception | A malicious app or log captures the code | PKCE with S256 |
| Code injection | An attacker slips their own code into a victim’s session | PKCE, and state or nonce bound to the session |
| CSRF on the callback | An attacker logs a victim into the attacker’s account | state or PKCE, as RFC 9700 describes |
| Open redirect | A loose redirect URI sends codes to an attacker | Exact redirect URI matching, and no open redirectors |
| Mix-up | A client talking to several servers sends a code to the wrong one | The iss response parameter (RFC 9207) |
| Token leakage in URLs | Tokens in query strings leak through logs and referrers | Code flow only, and tokens in headers or POST bodies |
| Token replay | A stolen token is used from another machine | Short lifetimes, DPoP or mTLS, refresh token rotation |
| ID token forgery | A forged or alg: none token is accepted |
Full validation with a pinned algorithm |
| Audience confusion | A token for API A is accepted by API B | Audience checks, and resource indicators (RFC 8707) |
| Token substitution | A client accepts a token issued to another client as a login | Use the ID token with aud and azp checks, never an access token |
| Confused deputy | An API forwards a user’s token to a downstream service | Token exchange (RFC 8693) for a narrower, downstream-specific token |
| Consent phishing | A malicious app asks users for broad scopes | Admin consent policies, app verification, scope review |
| Device code phishing | Attackers send victims real device codes | Limit the device flow to clients that need it |
Consent phishing deserves a closer look
Attackers do not always break OAuth. Often they use it exactly as designed. They register an app with a convincing name, send users a link, and ask for access to mail or files. A user who clicks “Allow” hands over a token, and no password or MFA prompt stands in the way.
Defend against it at the organization level. Restrict which users may consent to third-party apps, require admin approval for sensitive scopes, and review granted apps regularly. Most enterprise identity providers support all three.
15. Libraries and Providers
Client libraries
- JavaScript and TypeScript:
openid-clientandoauth4webapifor full OAuth flows, andjosefor JWT and JWK handling. All three are maintained by Filip Skokan, who also maintains a certified OIDC provider. - Frameworks: Auth.js and Better Auth for Next.js and similar stacks, and Spring Security for Java.
- Python: Authlib covers clients, servers, and JOSE.
- .NET: Microsoft.Identity.Web and the built-in OpenID Connect middleware in ASP.NET Core.
- Mobile: AppAuth for iOS and Android, which follows RFC 8252 out of the box.
Prefer libraries that are certified by the OpenID Foundation. Certification means the library passed the official conformance tests.
Authorization servers
- Self-hosted open source: Keycloak, Zitadel, Authentik, and Ory Hydra. Keycloak is the most widely deployed and the usual enterprise starting point. Zitadel and Authentik are lighter, more modern alternatives. Ory Hydra is a focused OAuth server that expects you to bring your own login and user management.
- Hosted services: Auth0 and Okta, Microsoft Entra ID, Amazon Cognito, Google Identity Platform, and many smaller providers.
Building your own authorization server is a large, security-critical project. The protocol details in this article are only the start. Account recovery, MFA, key rotation, abuse detection, and audit logging come next. Buy or self-host a mature product unless identity is your core business.
16. Common Mistakes
- Using the access token as proof of identity. Use the ID token for identity, and the access token only for APIs.
- Decoding a JWT without verifying it. A base64 decode proves nothing, because anyone can create a token.
- Trusting the
algheader. Pin the algorithms you accept. - Skipping the audience check. A token issued to another app or API must be rejected.
- Using
emailas the primary user key. Useissplussub. - Registering wildcard redirect URIs. Register exact URIs for every environment instead.
- Storing tokens in
localStorage. Use a BFF, or at least keep tokens in memory with short lifetimes. - Long-lived refresh tokens without rotation. Turn on rotation and set an absolute lifetime.
- Treating scopes as authorization. Check object ownership in your own code.
- Embedding a client secret in a mobile or browser app. Anything shipped to users is public, so rely on PKCE.
- Ignoring what happens at logout. Revoke refresh tokens and end the provider session when a user signs out.
- Never refreshing the key set. Your app breaks the day the provider rotates its signing keys.
17. Frequently Asked Questions
Is OAuth 2.1 a final standard yet?
Not yet, as of late November 2026, because it is still draft 17 with no RFC number. Its rules already match RFC 9700, which is a published Best Current Practice, so you can follow it today.
Do I still need state if I use PKCE?
RFC 9700 allows clients to rely on PKCE for CSRF protection once they have confirmed that the server supports PKCE. Many libraries send state anyway. It is cheap, and it also carries application data, such as the page to return to after sign-in.
Should my SPA use PKCE in the browser, or a BFF?
Use a BFF for anything that handles personal or business data, as RFC 10017 recommends. A pure browser client is acceptable for low-risk apps, with short token lifetimes, refresh token rotation, and a strict CSP.
What is the difference between an ID token and an access token?
The ID token tells your app who signed in, and its audience is your app. The access token lets your app call an API, and its audience is that API. Your app should validate the ID token and treat the access token as opaque.
Are JWTs secure?
The format is fine when validated correctly. The problems come from bad validation, such as trusting alg, skipping the audience check, or never expiring tokens. Treat any JWT as untrusted input until every check passes.
How does this relate to passkeys?
Passkeys authenticate the user to the authorization server. OAuth and OIDC then carry the result to your apps. They work together, so a provider that supports passkeys protects every app that signs in through it. My passkeys guide covers that side.
18. Conclusion
OAuth looks complex because it grew for a long time. The modern version is much simpler. Use the authorization code flow with PKCE everywhere, add OpenID Connect when you need identity, and drop the implicit and password grants for good.
Security comes from the checks, not the flow diagram. Validate every token fully, match redirect URIs exactly, restrict token audiences, and rotate refresh tokens. For browser apps, follow RFC 10017 and keep tokens on a backend for frontend.
Most of all, use a mature library and a mature authorization server. Your job is to configure them correctly and verify what they give you. The standards in this area are still moving, with OAuth 2.1 close to publication, so treat this guide as a snapshot from late November 2026.
19. References
Core standards
- IETF: The OAuth 2.1 Authorization Framework (draft 17)
- RFC 9700: Best Current Practice for OAuth 2.0 Security
- RFC 10017: OAuth 2.0 for Browser-Based Applications
- RFC 6749: The OAuth 2.0 Authorization Framework
- RFC 7636: Proof Key for Code Exchange (PKCE)
- RFC 8252: OAuth 2.0 for Native Apps
- OpenID Connect Core 1.0
Extensions
- RFC 9207: Authorization Server Issuer Identification
- RFC 9449: DPoP
- RFC 8705: Mutual-TLS Client Authentication and Certificate-Bound Tokens
- RFC 9126: Pushed Authorization Requests
- RFC 8707: Resource Indicators for OAuth 2.0
- RFC 9728: OAuth 2.0 Protected Resource Metadata
- RFC 9068: JWT Profile for OAuth 2.0 Access Tokens
- RFC 7662: Token Introspection
- RFC 8628: Device Authorization Grant
- RFC 8693: OAuth 2.0 Token Exchange
- OpenID Connect RP-Initiated Logout 1.0
- OpenID Connect Back-Channel Logout 1.0
- OpenID Foundation: FAPI 2.0 Security Profile
Libraries and guidance
- openid-client
- jose
- OpenID Foundation: certified implementations
- OWASP: OAuth 2.0 Cheat Sheet
- Model Context Protocol: authorization