Security & Identity
OpenID Connect: ID Tokens, Discovery, Nonce and Session Management
Intermediate7 min readUpdated
OpenID Connect turns OAuth 2.0 from a delegated-access framework into a single sign-on protocol by adding one thing an access token never provided: a verifiable statement about who signed in and how. This guide covers the ID token and its claims, the discovery document and key set, standard scopes and UserInfo, what nonce and state each protect against, logout and session management, and how to validate an ID token without cutting corners.
What you will learn
- Describe how OpenID Connect layers identity on top of the OAuth 2.0 authorization code flow
- Read an ID token and explain every mandatory claim it carries
- Use the discovery document and JWKS endpoint instead of hard-coding provider configuration
- Explain what nonce, state and the c_hash and at_hash claims each prevent
- Validate an ID token correctly and know when to use it rather than an access token
- Choose between front-channel and back-channel logout for a federated session
OAuth 2.0 gives an application permission to call an API. It does not tell that application who the user is, when they authenticated, or whether they are still there — the access token was minted for an API and may be opaque to everyone else. Applications nevertheless needed exactly that information, so for years they inferred identity by calling a provider-specific profile endpoint with the access token, an approach with a genuine flaw: an access token obtained anywhere, for any client, will happily answer such a call.
OpenID Connect fixes this by defining a second token that is addressed to the client itself. The ID token is a signed JSON Web Token whose audience is your application, whose issuer you have pinned, and whose claims describe the authentication event. Around that one idea the specification adds discovery, a standard set of claims and scopes, a UserInfo endpoint, and session and logout semantics — enough to build interoperable single sign-on across products from different vendors. This guide assumes you already know the OAuth 2.0 authorization code flow; everything here is what OpenID Connect adds on top of it.
What the protocol adds
An OpenID Connect request is an OAuth authorization request with the openid scope present. That single scope switches the provider into OpenID Connect mode, and the token response gains an id_token alongside the access token.
GET /authorize?response_type=code
&scope=openid%20profile%20email
&client_id=web-portal
&redirect_uri=https%3A%2F%2Fportal.example.com%2Fcallback
&state=Rm9vYmFy
&nonce=n-0S6_WzA2Mj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256 HTTP/1.1
Host: sso.example.com
The vocabulary shifts slightly: the authorization server is now the OpenID Provider (OP) and the client is the Relying Party (RP). The token endpoint response looks familiar with one addition.
{
"access_token": "IiFwYXNzZWQgdG8gdGhlIEFQSSI",
"token_type": "Bearer",
"expires_in": 300,
"refresh_token": "8xLOxBtZp8",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6InNpZy0yMDI2LTAzIn0.eyJpc3MiOi..."
}
Three response modes exist. The authorization code flow is the one to use: everything sensitive comes back on the back channel. The implicit flow and the hybrid flow return tokens through the browser and are effectively retired for new work, for the same reasons OAuth removed the implicit grant.
Inside the ID token
Decoding the payload of an ID token — with a client-side JWT decoder, never by trusting an unverified value in code — reveals the claims that carry the whole meaning of the protocol.
{
"iss": "https://sso.example.com",
"sub": "9f2c1b7e-4a55-4f2a-bd58-6f0f1a2c3d44",
"aud": "web-portal",
"exp": 1789012645,
"iat": 1789012345,
"auth_time": 1789012300,
"nonce": "n-0S6_WzA2Mj",
"acr": "urn:mace:incommon:iap:silver",
"amr": ["pwd", "hwk"],
"azp": "web-portal",
"email": "[email protected]",
"email_verified": true,
"name": "Jordan Lee",
"preferred_username": "jordan"
}
iss and sub together are the only stable identifier for a user. The subject is unique and never reused within one issuer, so a local account should be keyed on the pair, not on an email address that the person can change at any time. aud must equal your client identifier; azp names the authorized party when a token is issued for multiple audiences. auth_time records when the user actually authenticated rather than when the token was issued, which is what lets you demand a fresh login for a sensitive operation by sending max_age or prompt=login. acr and amr describe the strength and the methods of that authentication — pwd for a password, otp for a one-time code, hwk for a hardware key — and are how a relying party can insist on multi-factor authentication for administrative screens.
Standard scopes map to standard claim sets: profile covers name, picture, locale and similar; email covers email and email_verified; address and phone cover the obvious. Requesting only what you need keeps the consent screen honest and reduces the personal data you have to look after.
Discovery and keys
Nothing about a provider should be hard-coded except its issuer URL. From that, the discovery document at a well-known path gives every endpoint and capability.
GET /.well-known/openid-configuration HTTP/1.1
Host: sso.example.com
{
"issuer": "https://sso.example.com",
"authorization_endpoint": "https://sso.example.com/authorize",
"token_endpoint": "https://sso.example.com/token",
"userinfo_endpoint": "https://sso.example.com/userinfo",
"jwks_uri": "https://sso.example.com/.well-known/jwks.json",
"end_session_endpoint": "https://sso.example.com/logout",
"response_types_supported": ["code"],
"id_token_signing_alg_values_supported": ["RS256", "ES256"],
"scopes_supported": ["openid", "profile", "email", "offline_access"],
"code_challenge_methods_supported": ["S256"]
}
The jwks_uri serves the provider's public signing keys as a JSON Web Key Set. Each key carries a kid, and the token header names the kid used, so rotation is seamless: the provider publishes the new key before it starts signing with it, clients refetch the set when they meet an unknown kid, and the old key is withdrawn once outstanding tokens have expired. Cache the key set, respect its cache headers, and rate-limit refetches so an unknown kid cannot be used to hammer the provider.
Nonce, state and the hash claims
Three separate mechanisms guard three separate weaknesses, and they are frequently confused.
state is yours. You generate it, keep it in your session, and compare it when the browser comes back. It ensures the callback belongs to a flow this browser started, defeating cross-site request forgery on the redirect endpoint and login-CSRF, where an attacker tries to have you silently signed in as them.
nonce is copied by the provider into the ID token. When you compare the token's nonce with the value you stored, you prove the token was issued for this authentication attempt and cannot be replayed from another one. It is mandatory in the implicit and hybrid flows and strongly recommended in the code flow.
c_hash and at_hash appear when a code or access token travels alongside an ID token in the front channel. They are truncated hashes of those values, so the relying party can confirm that the code and token it received are the ones the provider issued together with this ID token.
PKCE remains in force on top of all of this; it protects the code exchange itself and is required by current OAuth best practice regardless of client type.
Validating an ID token properly
Validation is a checklist, and skipping any line has been the root cause of real vulnerabilities. Verify the signature with a key from the provider's JWKS selected by kid, restricting the accepted algorithms to those the provider advertises; check iss matches exactly; check aud contains your client identifier and, if azp is present, that it equals it; check exp and iat with a small clock skew allowance; compare nonce; and, if you asked for one, verify auth_time against your max_age.
// nimbus-jose-jwt: validator configured once from the discovery document
IDTokenValidator validator = new IDTokenValidator(
new Issuer("https://sso.example.com"),
new ClientID("web-portal"),
JWSAlgorithm.RS256,
new URL("https://sso.example.com/.well-known/jwks.json"));
try {
IDTokenClaimsSet claims = validator.validate(SignedJWT.parse(idToken), expectedNonce);
String subject = claims.getSubject(); // stable only together with the issuer
Date authenticatedAt = claims.getAuthenticationTime();
if (authenticatedAt.toInstant().isBefore(Instant.now().minus(Duration.ofMinutes(15)))) {
throw new ReauthenticationRequiredException(); // step-up for a sensitive action
}
} catch (BadJOSEException | JOSEException e) {
throw new AuthenticationFailedException("id_token rejected", e);
}
Write this yourself only if you have no alternative. A library — or the OpenID Connect client built into Spring Security — implements the full list, including the algorithm restrictions and the key-rotation behaviour that hand-rolled code usually omits. The related pitfalls in verifying any JWT, including algorithm confusion, are covered in securing REST APIs with JWT.
UserInfo, and which token goes where
The UserInfo endpoint returns claims about the authenticated user for a valid access token that carries the openid scope.
GET /userinfo HTTP/1.1
Host: sso.example.com
Authorization: Bearer IiFwYXNzZWQgdG8gdGhlIEFQSSI
It is useful when claims change during a session or when you deliberately keep the ID token small, but it costs a network call and its response must have a sub identical to the ID token's — otherwise a token substitution has occurred. Prefer claims in the ID token for anything you need on every request.
The division of labour is worth stating plainly, because getting it wrong is the most common OpenID Connect design error:
| Token | Audience | Purpose | Sent to |
|---|---|---|---|
| ID token | Your client | Who signed in, how and when | Nowhere — consumed by the client |
| Access token | An API | What the bearer may do there | The resource server |
| Refresh token | The provider | Obtain new tokens silently | The token endpoint only |
Sessions and logout
A federated login creates at least two sessions: one at the provider and one in each application. Ending them coherently is the part of single sign-on that implementations most often skip.
RP-initiated logout sends the user to the provider's end_session_endpoint with id_token_hint and a post_logout_redirect_uri, ending the provider session and returning the user to a page you registered in advance.
Front-channel logout has the provider load a logout URL for each application in a hidden iframe. It is simple, but it depends on third-party cookies and on every iframe loading successfully, so it fails quietly in modern browsers.
Back-channel logout is the dependable option. The provider POSTs a signed logout token — a JWT with a sid or sub and an events claim naming the logout event — directly to each registered client, server to server.
POST /backchannel-logout HTTP/1.1
Host: portal.example.com
Content-Type: application/x-www-form-urlencoded
logout_token=eyJhbGciOiJSUzI1NiIsImtpZCI6InNpZy0yMDI2LTAzIn0...
Validate that token exactly as you validate an ID token, with the extra rule that it must not contain a nonce, then destroy the local session identified by sid. Because this requires per-session bookkeeping, applications that rely purely on stateless cookies have to add a server-side session index — a fair price for logout that actually works. If you are integrating with an older enterprise provider, the equivalent mechanism there is single logout in SAML, which faces the same difficulties in a more complicated form.
Key takeaways
- OpenID Connect is OAuth 2.0 plus the
openidscope, an ID token addressed to your client, and standard identity claims. - The ID token tells you who authenticated, when, and by which methods;
issandsubtogether are the only stable user key. - Read every endpoint and key from the discovery document and JWKS so that rotation and provider changes need no redeploy.
statebinds the redirect to your session,noncebinds the ID token to this login attempt, PKCE binds the code to your client — use all three.- Validate signature, issuer, audience, expiry, nonce and, where relevant,
auth_time; use a library rather than hand-written checks. - Send access tokens to APIs and keep ID tokens in the client, and implement back-channel logout if single sign-out has to be reliable.
Sources and further reading
Frequently asked questions
- Should I send the ID token to my API?
- No. The ID token is addressed to the client application — its audience is your client identifier — and it exists to tell that application who logged in. APIs must accept access tokens, whose audience names the API and whose scopes describe what the caller may do. Sending an ID token to an API forces the API to accept a token that was never scoped for it, which breaks audience validation.
- What is the difference between nonce and state?
- State protects the redirect back to your application: you generate it, store it in the session and compare it on return, which stops an attacker from initiating a flow that completes in a victim's browser. Nonce protects the ID token itself: the provider copies it into the token, so a token replayed from a different login attempt fails the comparison. Both are required in practice.
- Can I trust the email claim from any provider?
- Only when email_verified is true and you trust that specific issuer to have verified it. Matching accounts on an unverified email is a well-known account-takeover path, because a user can register an address they do not control at a loosely governed provider. Key local accounts on the issuer plus subject pair, and treat email as a display attribute you may update after verification.
- How do I know when a federated session has ended?
- You cannot infer it from token expiry. Back-channel logout is the reliable mechanism: the provider POSTs a signed logout token to each client that registered a logout endpoint, and the client destroys the matching local session. Front-channel logout uses hidden iframes and is easier to deploy but unreliable when third-party cookies or the network are restricted.