"Log in with Google", an API that rejects your request with 401, a token that starts with eyJ: almost every modern application touches OAuth 2.0, OpenID Connect and JWT, yet the three are mixed up constantly. Teams use OAuth for login without the layer that was built for it, put access tokens into localStorage, or accept any token that carries a valid signature. These are not academic mistakes. They lead to account takeovers, leaked data and APIs that trust tokens issued for someone else.
This article walks through the whole picture in the order you need it: what each standard is for, who the participants are, what really happens on the wire during a login, what is inside a JWT, how to validate tokens properly, and how to apply all of it to browsers, mobile apps and microservices. Each step comes with real requests and code, so you can map the protocol onto the systems you build.
1. Three Standards, Three Different Jobs
The confusion starts with the names, so let us separate them first. Each of the three answers a different question.
| Standard | Question it answers | Result |
|---|---|---|
| OAuth 2.0 | May this application act on my behalf? | Access token |
| OpenID Connect | Who is the user who just logged in? | ID token |
| JWT | How do I package claims so they cannot be forged? | Signed token format |
OAuth 2.0 (RFC 6749) is a framework for delegated authorization. A user allows an application to access a resource, such as their calendar or their photos, without giving that application their password. The application receives an access token with limited rights, and the API that holds the data accepts that token. OAuth deliberately says nothing about who the user is. The access token is a key to a door, not an ID card.
OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0. It reuses the same flows but adds what OAuth leaves out: a standard way to tell the application who the user is, when they authenticated and how. The central addition is the ID token, plus a discovery document and a UserInfo endpoint. When you click "Log in with Google" or sign in to a company portal through Microsoft Entra ID, Okta or Keycloak, you are almost always using OpenID Connect.
JWT, the JSON Web Token (RFC 7519), is a data format, not a protocol. It is a compact, URL-safe way to transport a set of claims, usually signed so that the receiver can verify who issued it and that nobody changed it. OpenID Connect requires the ID token to be a JWT. Access tokens can be JWTs, but they can just as well be random strings that the API looks up.
Three misconceptions follow directly from mixing these up:
- "OAuth is a login protocol." Plain OAuth only proves that someone obtained a token for your client. Using an access token as proof of login led to real vulnerabilities in the past, because a token issued to another application could be replayed against yours. OpenID Connect fixes exactly this.
- "A JWT is secure." A JWT is only as trustworthy as the checks you run on it. The payload is merely encoded, not encrypted, and anyone can read it. A signature that you do not verify, or verify with the wrong key, protects nothing.
- "The access token tells my app who the user is." The access token is meant for the API, not for the client. Its format and content can change at any time, and a client must treat it as an opaque string.
Keep this split in mind for the rest of the article: OAuth gives access, OpenID Connect gives identity, and JWT is the envelope both often use.
2. The Participants: Roles in OAuth 2.0
OAuth describes every interaction with four roles. Once you can name them in your own system, most design questions become much easier.
| Role | What it is | Example |
|---|---|---|
| Resource owner | The person (or system) who owns the data and can grant access | You, as owner of a photo library |
| Client | The application that wants to access the data on the owner's behalf | A photo printing web shop |
| Authorization server | Authenticates the owner, asks for consent and issues tokens | Google, Keycloak, Microsoft Entra ID, Okta, Auth0 |
| Resource server | The API that holds the data and accepts access tokens | The cloud photo API |
Picture the classic example. A printing shop wants to read your cloud photos to print an album. Before OAuth, the shop would have asked for your cloud password, stored it, and gained unlimited access to everything, forever. With OAuth, the shop sends you to the authorization server of your cloud provider. You log in there, never on the shop's website, and you see a consent screen: "Print Shop wants to view your photos". If you agree, the shop receives a token that can read photos, cannot delete them, and expires after a while. You can revoke it at any time without changing your password.
Resource owner (user)
│ 1. wants to print photos
v
Client (print shop)
│ 2. redirects the user to the login
v
Authorization server (login + consent)
│ 3. user logs in and agrees
│ 4. access token for the client
v
Client (print shop)
│ 5. GET /photos
│ Authorization: Bearer <access token>
v
Resource server (photo API)
Two more terms appear everywhere.
Scopes describe what the client asks for, for example photos.read or calendar.write. The authorization server may grant fewer scopes than requested, and the resource server must check that the token carries the scope an endpoint requires. Scopes describe what the application may do on behalf of the user. They are not a complete permission system for the user (more on that in section 11).
Client types decide which flows are safe. A confidential client runs on a server and can keep a secret, such as a classic backend web application. A public client cannot keep a secret, because its code is in the hands of the user: single-page applications in the browser, mobile apps and desktop tools. Anything shipped to a device can be extracted, so a "secret" embedded in a mobile app is not a secret. This distinction is the reason PKCE exists, which we will look at next.
In many companies the roles collapse in practice. The same team runs the client and the API, and the authorization server is a central Keycloak or Entra ID tenant. The roles still matter, because each one has its own security duties. The client must protect tokens, the authorization server must issue the right ones, and the resource server must validate every single request.
3. Tokens and What Each One Is For
OAuth and OpenID Connect use a handful of artefacts that look similar but have very different purposes. Most security bugs come from using one in place of another.
| Artefact | Issued to | Read by | Typical lifetime | Purpose |
|---|---|---|---|---|
| Authorization code | Client, via the browser | Authorization server only | Seconds (max. ~1 minute), single use | Exchanged for tokens |
| Access token | Client | Resource server (API) | 5 to 60 minutes | Access to an API |
| Refresh token | Client | Authorization server only | Hours to months | Obtain new access tokens |
| ID token | Client | Client only | Minutes | Tells the client who logged in |
The authorization code is a short-lived, one-time voucher. It travels through the browser, which is an unsafe place, so it is useless on its own. Only the client can redeem it at the token endpoint, together with its credentials or its PKCE proof.
The access token is what the client sends to the API in the Authorization: Bearer header. It comes in two shapes:
- Self-contained (JWT): the API verifies the signature locally with the authorization server's public key and reads the claims directly. This is fast and needs no network call per request, but a token stays valid until it expires, even if the user's access was revoked in the meantime.
- Opaque (reference token): a random string with no meaning. The API asks the authorization server about it through the token introspection endpoint (RFC 7662). Revocation takes effect immediately, but every validation costs a network call, so APIs usually cache introspection results briefly.
Many authorization servers issue JWT access tokens by default. RFC 9068 standardises their format and marks them with the type at+jwt, so they cannot be confused with ID tokens.
The refresh token lets the client get a new access token without sending the user through the login again. It is the most valuable token, because it lives long, so it must never be sent to an API and must be stored with the most care. Section 8 covers rotation and revocation.
The ID token exists only in OpenID Connect. It is a JWT addressed to the client: its aud claim contains the client's ID. The client validates it once after login, reads who the user is, and creates its own session. It is not meant for APIs, and an API must reject it, because its audience is the client, not the API.
A simple rule keeps these apart. Access tokens go to APIs. ID tokens stay in the client. Refresh tokens only ever go back to the authorization server.
4. The Authorization Code Flow with PKCE, Step by Step
The authorization code flow with PKCE is the flow you should use for every application in which a user logs in: server-side web apps, single-page apps, mobile and desktop apps. The current security best practice (RFC 9700) and the upcoming OAuth 2.1 recommend it for all of them. Here is what happens on the wire. The numbers match the five steps below.
Browser Client Auth server API
│ │ │ │
│─ click ─────>│ │ │
│ │ 1 state, │ │
│ │ nonce, PKCE │ │
│< 2 302 ──────│ │ │
│─ 2 GET /authorize ─────────>│ │
│< 2 login, MFA ─────────────>│ │
│< 3 code, state ─────────────│ │
│─ 3 code ────>│ │ │
│ │─ 4 /token ──>│ │
│ │< 4 tokens ───│ │
│ │─ 5 Bearer token ─────────>│
│ │< 5 200 OK ────────────────│
Step 1: The client prepares the request
Before redirecting, the client creates three random values and keeps them in the user's session:
stateprotects against cross-site request forgery. The client accepts a callback only if it carries the samestateit sent.nonce(OpenID Connect) is copied by the authorization server into the ID token. It ties the ID token to this login attempt and prevents replay.code_verifieris a high-entropy secret for PKCE (Proof Key for Code Exchange, RFC 7636). The client sends only its SHA-256 hash, thecode_challenge, in this step.
Generating the PKCE pair takes a few lines with the Web Crypto API, available in browsers and Node.js:
function base64url(bytes: Uint8Array): string {
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export async function createPkcePair(): Promise<{ verifier: string; challenge: string }> {
// 32 random bytes -> a 43-character verifier (RFC 7636 allows 43 to 128 characters)
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
return { verifier, challenge: base64url(new Uint8Array(digest)) };
}
Step 2: The browser goes to the authorization endpoint
The client redirects the browser to the authorization server. Line breaks are added for readability:
GET /realms/shop/protocol/openid-connect/auth
?response_type=code
&client_id=shop-web
&redirect_uri=https%3A%2F%2Fshop.example.com%2Fcallback
&scope=openid%20profile%20email%20orders.read
&state=af0ifjsldkj
&nonce=n-0S6_WzA2Mj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
Host: login.example.com
response_type=code selects the authorization code flow. The openid scope turns the request into an OpenID Connect request, so an ID token will be issued. redirect_uri must match one of the addresses registered for the client exactly. The authorization server now authenticates the user with whatever it requires: password, passkey, multi-factor authentication or a corporate single sign-on session. The client never sees any of it.
Step 3: The user comes back with a code
After a successful login (and consent, if required), the authorization server redirects the browser back:
HTTP/1.1 302 Found
Location: https://shop.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=af0ifjsldkj&iss=https%3A%2F%2Flogin.example.com%2Frealms%2Fshop
The client first checks that state matches the value in the session. If the authorization server sends the iss parameter (RFC 9207), the client also checks that it is the expected issuer. This prevents mix-up attacks in applications that work with several authorization servers.
Step 4: The client exchanges the code for tokens
Now the client talks to the token endpoint directly, server to server or from the app, without the browser's address bar in between:
POST /realms/shop/protocol/openid-connect/token
Host: login.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic c2hvcC13ZWI6c2VjcmV0 (confidential clients only)
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fshop.example.com%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
The authorization server hashes the code_verifier and compares it with the code_challenge from step 2. Only the party that started the login knows the verifier, so a stolen code is worthless to an attacker. The response contains the tokens:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6IjIwMjYtMDUifQ...",
"token_type": "Bearer",
"expires_in": 300,
"refresh_token": "8xLOxBtZp8...",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjYtMDUifQ...",
"scope": "openid profile email orders.read"
}
Step 5: The client validates the ID token and calls the API
The client validates the ID token (signature, issuer, audience, expiry and the nonce from step 1) and creates its own session for the user. From now on it calls the API with the access token:
GET /api/orders
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6IjIwMjYtMDUifQ...
Why PKCE and not the older flows
The authorization code travels through the browser, so it can leak: through a malicious app that registered the same custom URL scheme on a phone, a browser extension, logs or the referrer header. Without PKCE, whoever has the code can redeem it. With PKCE, the code is bound to a secret that never left the client. This is why PKCE is now recommended even for confidential clients, which additionally authenticate with their secret.
The implicit flow, which returned tokens directly in the redirect URL, is deprecated. Tokens in URLs end up in browser history, logs and referrer headers, and the flow had no way to bind them to the client. The resource owner password credentials grant, in which the app collects the user's password itself, is deprecated as well. It trains users to type their password into third-party forms and makes multi-factor authentication and single sign-on impossible. Neither is part of OAuth 2.1.
5. OpenID Connect: Adding Identity to OAuth
OpenID Connect takes the authorization code flow you just saw and standardises everything needed to log a user in. For the client, three pieces matter.
The ID token
The ID token is a signed JWT that describes the authentication event. Decoded, its payload looks like this:
{
"iss": "https://login.example.com/realms/shop",
"sub": "248289761001",
"aud": "shop-web",
"exp": 1795862400,
"iat": 1795862100,
"auth_time": 1795862095,
"nonce": "n-0S6_WzA2Mj",
"acr": "urn:example:mfa",
"amr": ["pwd", "otp"],
"name": "Jane Doe",
"email": "jane.doe@example.com",
"email_verified": true
}
| Claim | Meaning |
|---|---|
iss | Issuer: exactly which authorization server created the token |
sub | Subject: the stable, unique ID of the user at this issuer |
aud | Audience: the client ID the token is meant for |
exp, iat | Expiry and issue time, in seconds since 1970 |
auth_time | When the user actually authenticated (may be earlier than iat with single sign-on) |
nonce | The value the client sent in the authorization request |
acr, amr | How strongly and by which methods the user was authenticated |
One rule saves a lot of trouble later: identify users by the pair iss + sub, never by e-mail. E-mail addresses change, get reassigned when someone leaves a company, and some providers let users enter unverified addresses. The sub is guaranteed to be unique and stable per issuer. Store it as the link between the external identity and your own user record, and treat the e-mail as a changeable attribute.
Scopes and the UserInfo endpoint
OpenID Connect defines standard scopes that request groups of user claims: openid (required), profile (name, picture, locale and similar), email, address and phone. Depending on the provider, these claims appear in the ID token or have to be fetched from the UserInfo endpoint with the access token:
GET /realms/shop/protocol/openid-connect/userinfo
Host: login.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6IjIwMjYtMDUifQ...
Discovery and keys
Every OpenID provider publishes a discovery document at a fixed address below its issuer URL. It lists all endpoints, supported algorithms and the location of the public keys:
GET https://login.example.com/realms/shop/.well-known/openid-configuration
{
"issuer": "https://login.example.com/realms/shop",
"authorization_endpoint": "https://login.example.com/realms/shop/protocol/openid-connect/auth",
"token_endpoint": "https://login.example.com/realms/shop/protocol/openid-connect/token",
"userinfo_endpoint": "https://login.example.com/realms/shop/protocol/openid-connect/userinfo",
"jwks_uri": "https://login.example.com/realms/shop/protocol/openid-connect/certs",
"end_session_endpoint": "https://login.example.com/realms/shop/protocol/openid-connect/logout",
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"id_token_signing_alg_values_supported": ["RS256", "ES256"]
}
The jwks_uri points to a JSON Web Key Set: the public keys the provider signs tokens with. Clients and APIs download it, cache it, and pick the right key by the kid (key ID) in each token's header. When the provider rotates its keys, it publishes the new key alongside the old one for a while, so tokens signed with either remain valid during the switch. This is why libraries only need the issuer URL to configure themselves: everything else follows from discovery.
6. Inside a JWT
A JWT looks like a long random string, but it is three Base64url-encoded parts separated by dots: header, payload and signature.
eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6IjIwMjYtMDUifQ <- header
.
eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUuY29tL3JlYWxtcy9zaG9wIiwic3ViIjoiMjQ4Mjg5NzYxMDAxIiwiYXVkIjoib3JkZXJzLWFwaSIsImNsaWVudF9pZCI6InNob3Atd2ViIiwic2NvcGUiOiJvcGVuaWQgb3JkZXJzLnJlYWQiLCJpYXQiOjE3OTU4NjIxMDAsImV4cCI6MTc5NTg2MjQwMCwianRpIjoiN2MxZTRmMmEtMmI5ZC00YzFlLTlmN2EtMWQyYzNiNGE1ZTZmIn0 <- payload
.
NHVaYe26MbtOYhSKkoKYdFVomg4i8ZJd8_-RU8VNbftc4TSMb4bXP3l3YlNWACwyXPGffz5aXHc6lty1Y2t4SWRqGteragsVdZufDn5BlnJl9pdR... <- signature
In a real request the three parts are written in one line, joined by the dots. Decoded, the header and payload are plain JSON:
{ "alg": "RS256", "typ": "at+jwt", "kid": "2026-05" }
{
"iss": "https://login.example.com/realms/shop",
"sub": "248289761001",
"aud": "orders-api",
"client_id": "shop-web",
"scope": "openid orders.read",
"iat": 1795862100,
"exp": 1795862400,
"jti": "7c1e4f2a-2b9d-4c1e-9f7a-1d2c3b4a5e6f"
}
The header names the signing algorithm (alg), the token type (typ) and the key that was used (kid). The payload holds the claims. The signature is computed over the first two parts. Change a single character in the header or payload, and the signature no longer matches.
The most important fact about JWTs is easy to forget: Base64url is an encoding, not encryption. Anyone who has the token can read every claim. Paste a token into a decoder such as the JWT Decoder and you see its full content. Never put secrets, passwords or sensitive personal data into a signed JWT. If the content itself must be confidential, it has to be encrypted (JWE, a separate format), which most access tokens are not.
Signing algorithms
| Algorithm | Type | Key | When to use |
|---|---|---|---|
| RS256 | RSA signature with SHA-256 | Private key signs, public key verifies | The common default, supported everywhere |
| PS256 | RSA-PSS with SHA-256 | Same as RS256 | More modern RSA padding, increasingly required in finance APIs |
| ES256 | ECDSA on the P-256 curve | Private key signs, public key verifies | Smaller keys and signatures, good default for new systems |
| EdDSA (Ed25519) | Edwards-curve signature | Private key signs, public key verifies | Fast and modern, check library support first |
| HS256 | HMAC with SHA-256 | One shared secret signs and verifies | Only when issuer and verifier are the same system |
With asymmetric algorithms (RS, PS, ES, EdDSA), only the authorization server holds the private key, and every API can verify tokens with the public key from the JWKS. With HS256, every party that can verify a token can also create one, because it is the same secret. That is acceptable inside one application, but never when many services must check tokens from a central issuer.
7. Validating Tokens Correctly
A resource server that receives a JWT access token must run a fixed list of checks on every request. Skipping any one of them has led to real-world breaches.
- Parse defensively. The token must have exactly three parts, and each part must decode. Reject anything else.
- Check the algorithm against an allow-list. Accept only the algorithms you expect, for example
RS256andES256. Never trust thealgheader on its own, and never acceptnone. - Verify the signature with a key from the issuer's JWKS, selected by
kid. Load the JWKS only from the URL you configured, never from a URL inside the token (headers such asjkuorx5umust be ignored unless you deliberately allow-listed them). - Check
iss. It must equal the issuer you trust, character for character. - Check
aud. It must contain this API's identifier. Without this check, any token from the same issuer, issued for any other application, is accepted by your API. - Check
expandnbfwith a small clock skew of a minute at most. - Check the token type if your issuer sets it:
at+jwtfor access tokens per RFC 9068. This stops an ID token from being used as an access token. - Check scopes and other claims that the specific endpoint needs, such as
orders.readfor reading orders.
You should not write this logic yourself. Use a maintained library and give it the expected issuer, audience and algorithms. In Spring Boot, a resource server needs little more than configuration:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://login.example.com/realms/shop
audiences: orders-api
Spring Security loads the discovery document from the issuer, fetches and caches the JWKS, verifies the signature, and checks issuer, audience and expiry. Authorization rules then refer to scopes, which Spring maps to authorities with the prefix SCOPE_:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAuthority("SCOPE_orders.read")
.requestMatchers(HttpMethod.POST, "/api/orders/**").hasAuthority("SCOPE_orders.write")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // no cookies: every request carries a bearer token
return http.build();
}
}
A controller can then read the validated claims directly:
@RestController
@RequestMapping("/api/orders")
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) {
this.orders = orders;
}
@GetMapping
List<OrderDto> myOrders(@AuthenticationPrincipal Jwt jwt) {
// iss + sub identify the user; never trust a user ID sent in the request body
return orders.findForUser(jwt.getIssuer().toString(), jwt.getSubject());
}
}
In Node.js, the jose library does the same work. Note the explicit issuer, audience and algorithm list:
import { createRemoteJWKSet, jwtVerify } from "jose";
const ISSUER = "https://login.example.com/realms/shop";
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/protocol/openid-connect/certs`));
export async function verifyAccessToken(token: string) {
const { payload } = await jwtVerify(token, jwks, {
issuer: ISSUER,
audience: "orders-api",
algorithms: ["RS256", "ES256"],
typ: "at+jwt",
clockTolerance: 30, // seconds
});
return payload; // validated claims: sub, scope, exp ...
}
If the typ check fails with your provider, look at a real token first: not every authorization server sets at+jwt yet. In that case, drop the option and make sure the audience check is strict instead.
8. Refresh Tokens, Lifetimes and Revocation
A self-contained access token cannot be taken back once it is issued: every API that validates it locally will accept it until exp. The standard answer is to keep access tokens short-lived and let the client renew them with a refresh token.
POST /realms/shop/protocol/openid-connect/token
Host: login.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token
&refresh_token=8xLOxBtZp8...
&client_id=shop-web
The authorization server checks that the refresh token is still valid, that the user's session or consent still exists, and that the account has not been disabled. Only then does it issue a new access token. This turns the refresh into a regular checkpoint: disable a user, and their access ends at the latest when the current access token expires.
Reasonable starting values:
| Token | Typical lifetime | Reasoning |
|---|---|---|
| Access token | 5 to 15 minutes | Limits the damage of a leaked token; refresh is cheap |
| Refresh token (web app) | Bound to the login session, e.g. 8 to 12 hours of activity | The user should not be logged out while working |
| Refresh token (mobile app) | Days to weeks, with rotation | Users expect to stay logged in |
| ID token | A few minutes | Only used once, right after login |
Rotation and reuse detection
For public clients, refresh tokens should be rotated: every refresh returns a new refresh token and invalidates the old one. If an attacker steals a refresh token and uses it, either the attacker or the real client will later present an already used token. A good authorization server detects this reuse and revokes the whole token family, which logs out the attacker and the user alike. The user has to log in again, and the stolen token is dead.
Sender-constrained tokens
A bearer token works for whoever holds it, like cash. Two standards bind a token to a key that only the legitimate client has:
- DPoP (RFC 9449): the client signs a small proof JWT for every request with a private key it keeps in the browser or app. The token contains a hash of the matching public key, so a stolen token is useless without the private key.
- Mutual TLS (RFC 8705): the token is bound to the client's TLS certificate. Common in banking and service-to-service traffic.
Both add complexity, so they are mostly used where the damage of a stolen token is high, as in open banking and healthcare, or in public clients that keep long-lived sessions.
Revocation and logout
The client can actively revoke a refresh token at the revocation endpoint (RFC 7009), for example when the user logs out. Logging out completely is harder than it looks, because there are several sessions: the client's own session, the session at the authorization server (single sign-on) and possibly sessions in other applications of the same login. OpenID Connect defines RP-initiated logout, where the client sends the user to the provider's end_session_endpoint, and back-channel logout, where the provider notifies every client server to server. If "log out everywhere" is a requirement, design for it early. It rarely works by accident.
9. Other Grant Types and When to Use Them
The authorization code flow covers every case with a user in front of a browser or app. For the other cases, OAuth offers specialised grant types.
| Grant type | Use case | User involved? |
|---|---|---|
| Authorization code + PKCE | Web, single-page, mobile and desktop apps with a user login | Yes |
| Client credentials | Service-to-service calls, batch jobs, integrations | No |
| Device authorization (RFC 8628) | TVs, CLI tools, devices without a browser or keyboard | Yes, on a second device |
| Token exchange (RFC 8693) | A service calls another service on behalf of the user | Indirectly |
| Refresh token | Renewing an access token | No (reuses the earlier consent) |
| Implicit, password | Deprecated, do not use |
Client credentials
When there is no user, a backend service authenticates as itself and receives a token for its own rights:
curl -s -X POST https://login.example.com/realms/shop/protocol/openid-connect/token \
-u "billing-job:${BILLING_JOB_SECRET}" \
-d grant_type=client_credentials \
-d scope=invoices.write
{ "access_token": "eyJhbGciOiJSUzI1NiIs...", "token_type": "Bearer", "expires_in": 300, "scope": "invoices.write" }
There is no refresh token: the service simply requests a new access token when the old one expires. Good client libraries cache the token and renew it shortly before expiry, instead of requesting a new one for every call. Keep the client secret in a secret store, not in the repository, or better, replace it with a private key and a signed client assertion (private_key_jwt), so no shared secret exists at all.
Device authorization
A smart TV cannot show a comfortable login form. With the device flow, it asks the authorization server for a code and shows the user a short instruction:
Go to https://login.example.com/device
and enter the code: WDJB-MJHT
The user opens that address on their phone, logs in there with all the usual protections, and enters the code. Meanwhile, the TV polls the token endpoint until the login is complete. The same flow works well for command-line tools that run on remote servers.
Token exchange
In a chain of services, the first API receives the user's token, but should it forward that token to the next service? Passing it on unchanged works, but the downstream service then accepts a token whose audience was another API, and every service along the chain holds a token that could call all the others. Token exchange solves this: the first service presents the incoming token to the authorization server and receives a new, narrower token for exactly the next service, still carrying the user's identity. Section 11 shows where this fits.
10. Where Tokens Live: Browsers, Single-Page Apps and Mobile Apps
The protocol only gets the tokens to the client. Keeping them safe there is a separate decision, and it differs by platform.
Single-page applications
A JavaScript application in the browser is a public client. It can run the authorization code flow with PKCE itself, but then it has to keep the tokens somewhere in the browser:
- localStorage or sessionStorage: readable by every script on the page. A single cross-site scripting flaw, or one compromised npm dependency, can send all tokens to an attacker.
- In memory only: much better, because the tokens vanish when the tab closes and are harder to reach. But the user has to log in again after a reload unless the app can silently renew its session.
For applications that handle sensitive data, the recommended approach is a Backend for Frontend (BFF). A small server-side component, often part of the web server that serves the app anyway, runs the OAuth flow as a confidential client and keeps all tokens on the server. The browser only receives a session cookie:
Browser (SPA)
│ cookie: HttpOnly, Secure, SameSite=Lax
v
BFF (server side, keeps all tokens)
│ Authorization: Bearer <access token>
v
APIs
Because the cookie is HttpOnly, JavaScript cannot read it, so a cross-site scripting bug cannot steal a token. The BFF attaches the access token when it forwards API calls and refreshes it in the background. Cookie-based sessions bring back the need for CSRF protection, which SameSite cookies and an anti-CSRF header cover. Frameworks such as Spring Cloud Gateway, Duende BFF or the session handling of Next.js and similar full-stack frameworks make this pattern straightforward.
Mobile and desktop apps
Native apps should follow RFC 8252: open the login page in the system browser (or an in-app browser tab such as ASWebAuthenticationSession on iOS and Custom Tabs on Android), never in an embedded web view. In a web view, the app could read the password the user types, and the user cannot see the real address bar. The redirect back into the app uses a claimed HTTPS link (universal links or app links), which is safer than a custom URL scheme, and PKCE protects the code. Tokens belong in the platform's secure storage: the Keychain on iOS and the Keystore on Android.
| Client | Recommended approach | Token storage |
|---|---|---|
| Server-side web app | Code flow + PKCE, confidential client | Server-side session |
| Single-page app, sensitive data | BFF, confidential client on the server | Server-side; browser has HttpOnly cookie |
| Single-page app, low risk | Code flow + PKCE in the browser | Memory, refresh token rotation |
| Mobile / desktop app | Code flow + PKCE via system browser | Keychain / Keystore |
| Backend service, no user | Client credentials | Memory, renewed before expiry |
11. Securing APIs and Microservices
A single API validating tokens is straightforward. A system of twenty services raises new questions: where to validate, which token to pass on, and how much authorization logic belongs in the token.
Validate at the edge and in every service
An API gateway can validate tokens before requests reach the services, and it should, because it stops invalid traffic early. But services should still validate the token themselves, at least signature, issuer, audience and expiry. Otherwise, any request that reaches a service by another path, such as an internal network or a misconfigured route, is trusted blindly. Validating a JWT locally costs microseconds once the JWKS is cached, so there is little reason to skip it.
One audience per API
Give every API its own audience and let each one accept only tokens issued for it. A token for the reporting API must not open the payment API. Without separate audiences, one leaked token works everywhere, and one compromised service can impersonate the user towards all others.
Calling downstream services
There are three common patterns, from simplest to safest:
- Forward the user's token unchanged. Simple, but every service in the chain must accept the same audience, which weakens the point above.
- Use the service's own client credentials token. Clear and safe for system tasks, but the downstream service no longer knows which user the call is for.
- Token exchange. The calling service swaps the incoming token for a new one, issued for the downstream API, still carrying the user's identity and limited to the scopes needed.
Scopes are not permissions
It is tempting to put every permission into the token: roles, tenant IDs, the list of projects a user may edit. This works for a while, then tokens grow to several kilobytes and get rejected by proxies with header limits, and every permission change only takes effect after the next token refresh. Use scopes for coarse, application-level rights such as orders.read. Decide fine-grained questions, like whether this user may edit this specific order, inside the service from its own data or with a dedicated policy engine. The token says who is calling and roughly what they may do; the service decides the rest.
Identity in asynchronous messages
Events published to Kafka or RabbitMQ are processed later, often long after the original access token expired, so do not put bearer tokens into messages. Store the relevant identity facts in the event itself, such as the user's subject and tenant, and authenticate the producer and consumer at the broker level. The article on event-driven architecture covers how to design such event contracts.
12. Common Mistakes and How Attacks Exploit Them
Most incidents around OAuth and JWT do not break cryptography. They exploit a missing check or an unsafe default. The following list covers the mistakes that appear again and again in reviews and penetration tests.
| Mistake | What an attacker does | Fix |
|---|---|---|
Accepting alg: none | Removes the signature and edits the claims freely | Allow-list algorithms in the validator |
| Algorithm confusion (RS256 vs HS256) | Signs a token with HS256 using the public RSA key as the HMAC secret | Fix the expected algorithm per key; use a current library |
| No audience check | Replays a token issued for another app of the same provider | Validate aud against this API's identifier |
Wildcard or prefix redirect_uri | Redirects the code to an attacker-controlled page | Register exact redirect URIs, compare exactly |
Missing state | Logs the victim into the attacker's account (login CSRF) | Random state per request, checked on callback |
| No PKCE | Redeems an intercepted authorization code | PKCE with S256 for every client |
| ID token used as API credential | Uses a token meant for one client against an API | APIs accept only access tokens for their audience |
| Tokens in URLs or logs | Picks tokens from logs, browser history or referrers | Tokens only in headers or POST bodies; redact logs |
| Tokens in localStorage | Steals tokens through cross-site scripting | BFF with HttpOnly cookies, or in-memory storage |
| Users matched by e-mail | Takes over an account by registering the same e-mail at another provider | Link accounts by iss + sub only |
| Long-lived access tokens | Keeps using a leaked token for days | Short access tokens, refresh with rotation |
Two of these deserve a closer look, because they surprise even experienced developers.
Algorithm confusion. An API expects RS256 tokens and verifies them with the provider's public key. An attacker creates a token with alg: HS256 and signs it with HMAC, using the public key, which is public by definition, as the secret. A naive library reads alg from the token, sees HS256, and verifies the HMAC with the same key material it was given. The signature matches, and the forged token is accepted. Modern libraries prevent this by tying keys to algorithms, but only if you configure the expected algorithms instead of trusting the header.
Account linking by e-mail. An application lets users log in with several providers and merges accounts that share an e-mail address. An attacker creates an account at a provider that does not verify e-mail addresses, enters the victim's address, and logs in. The application links the attacker to the victim's existing account. Always link identities by issuer and subject. If you must merge accounts, require the user to log in with both identities first, and only trust email when email_verified is true and the provider is known to verify it.
13. A Complete Example: Spring Boot, Keycloak and a Web Client
The fastest way to understand the flows is to watch them run locally. Keycloak, an open-source identity provider, starts with one command:
docker run --name keycloak -p 8180:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=change-me \
quay.io/keycloak/keycloak:26.0 start-dev
In the admin console at http://localhost:8180, create a realm shop, a user with a password, a confidential client shop-web with the redirect URI http://localhost:8080/login/oauth2/code/keycloak, and a client scope orders.read. The issuer of the realm is then http://localhost:8180/realms/shop, and its discovery document is available below that address.
The web application as an OpenID Connect client
A Spring Boot application with the spring-boot-starter-oauth2-client dependency becomes a login-capable client through configuration:
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: shop-web
client-secret: ${SHOP_WEB_CLIENT_SECRET}
authorization-grant-type: authorization_code
scope: openid, profile, email, orders.read
provider:
keycloak:
issuer-uri: http://localhost:8180/realms/shop
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
SecurityFilterChain web(HttpSecurity http, ClientRegistrationRepository registrations) throws Exception {
var resolver = new DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization");
resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/public/**").permitAll()
.anyRequest().authenticated())
.oauth2Login(login -> login.authorizationEndpoint(a -> a.authorizationRequestResolver(resolver)));
return http.build();
}
}
Spring Security now redirects unauthenticated users to Keycloak, handles state and nonce, adds PKCE (also for this confidential client, thanks to the customizer), exchanges the code, validates the ID token and creates a session. Tokens never reach the browser: the user only gets a session cookie, which is the BFF pattern from section 10. To call the orders API with the user's access token, inject the authorized client:
@Controller
class OrdersPageController {
private final RestClient api = RestClient.create("http://localhost:8081");
@GetMapping("/orders")
String orders(@RegisteredOAuth2AuthorizedClient("keycloak") OAuth2AuthorizedClient client, Model model) {
List<?> orders = api.get()
.uri("/api/orders")
.headers(h -> h.setBearerAuth(client.getAccessToken().getTokenValue()))
.retrieve()
.body(List.class);
model.addAttribute("orders", orders);
return "orders";
}
}
The orders API itself is the resource server from section 7: issuer-uri and audiences in the configuration, scope rules in the security filter chain. Make sure Keycloak puts the API's identifier into the token's audience, using an audience mapper on the client scope, otherwise the audience check rejects every token, which is the correct behaviour.
Watching it work
Log in once, then decode the access token and the ID token in a JWT decoder and compare them: different aud, different typ, different purpose. Call the API without a token (401), with the ID token (401, wrong audience), with a token lacking the scope (403) and with the right token (200). Ten minutes of this teaches more about the protocol than any diagram.
14. Conclusion and a Practical Checklist
OAuth 2.0, OpenID Connect and JWT look complicated because they are often explained together, but each solves one clear problem. OAuth hands out limited, revocable access to APIs. OpenID Connect adds a verified answer to "who is this user?". JWT is the signed envelope in which both often deliver their claims. Most real-world security problems do not come from the standards themselves, but from skipped checks and from tokens used for the wrong purpose.
If you remember only three things, make it these: use the authorization code flow with PKCE for every user login, let every API validate issuer, audience, signature and expiry on every request, and keep tokens out of places where scripts, logs or URLs can reach them.
Use this checklist when you build or review a system:
- Every user login uses the authorization code flow with PKCE (S256); implicit and password grants are gone.
- Redirect URIs are registered exactly, without wildcards.
- The client checks
state, and validates the ID token includingnonce. - Users are identified by
iss+sub, not by e-mail. - APIs validate signature, allowed algorithms,
iss,aud,expand required scopes on every request. - Every API has its own audience; ID tokens are rejected by APIs.
- Access tokens live 5 to 15 minutes; refresh tokens are rotated for public clients.
- Browser apps with sensitive data use a BFF with HttpOnly cookies instead of tokens in localStorage.
- Mobile apps log in through the system browser and keep tokens in Keychain or Keystore.
- Service-to-service calls use client credentials or token exchange, with secrets in a secret store.
- Tokens never appear in URLs, logs or error messages.
- Logout and account deactivation are tested end to end, including single sign-on sessions.
References
- RFC 6749, The OAuth 2.0 Authorization Framework: https://www.rfc-editor.org/rfc/rfc6749
- RFC 6750, Bearer Token Usage: https://www.rfc-editor.org/rfc/rfc6750
- RFC 7519, JSON Web Token (JWT): https://www.rfc-editor.org/rfc/rfc7519
- RFC 7636, Proof Key for Code Exchange (PKCE): https://www.rfc-editor.org/rfc/rfc7636
- RFC 8252, OAuth 2.0 for Native Apps: https://www.rfc-editor.org/rfc/rfc8252
- RFC 8628, Device Authorization Grant: https://www.rfc-editor.org/rfc/rfc8628
- RFC 8693, Token Exchange: https://www.rfc-editor.org/rfc/rfc8693
- RFC 9068, JWT Profile for OAuth 2.0 Access Tokens: https://www.rfc-editor.org/rfc/rfc9068
- RFC 9449, Demonstrating Proof of Possession (DPoP): https://www.rfc-editor.org/rfc/rfc9449
- RFC 9700, Best Current Practice for OAuth 2.0 Security: https://www.rfc-editor.org/rfc/rfc9700
- OpenID Connect Core 1.0: https://openid.net/specs/openid-connect-core-1_0.html
- Spring Security OAuth2 reference: https://docs.spring.io/spring-security/reference/servlet/oauth2/index.html




