JWT resource servers
Validating a JWT: signature, issuer, audience, expiry, and the claims-to-authorities mapping. Also, what not to put in a token.
A JWT proves that somebody holding a key signed these claims, and they have not been altered since. That is all it proves, and most JWT mistakes come from believing it proves something else.
Read one without a key
Here is a token as it travels:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTE
xMzgiLCJlbWFpbCI6ImFuYUBleGFtcGxlLmNvbSIsInJvbGVzIjpbIkFETUlOIl0sImlzcyI6Imh0d
HBzOi8vYXV0aC5leGFtcGxlLmNvbSIsImF1ZCI6Im9yZGVycy1hcGkiLCJpYXQiOjE3ODgwMDAwMDA
sImV4cCI6MTc4ODAwMzYwMH0.RJG8rAey0j-In78v5x7zV2eOt2CqHRJIdeikQkMi5uMThree parts separated by dots. Split on the dots, base64-decode the first two, and no key is involved:
{"alg":"HS256","typ":"JWT"}
{"sub":"user-1138","email":"ana@example.com","roles":["ADMIN"],
"iss":"https://auth.example.com","aud":"orders-api",
"iat":1788000000,"exp":1788003600}That is the single most important fact about JWTs and the one most often forgotten: a JWT is signed, not encrypted. Every claim is public to anyone who sees the token — the user's browser, an intermediary, a log file, a bug report with a header pasted into it.
So the rule for what goes in a token is short. Nothing secret. Nothing you would mind publishing. Prefer an opaque subject id over an email address. And keep it small, because it travels on every request — a token with forty claims is forty claims of overhead per call.
What validation actually has to check
The signature is the first check and not the only one. A resource server has to answer is this token for me, from someone I trust, and still current — and each of those is a separate claim:
| Check | Claim | What goes wrong without it |
|---|---|---|
| signature | — | anyone can write any token |
| issuer | iss | a validly signed token from a different system is accepted |
| audience | aud | a token meant for another service of yours is accepted |
| expiry | exp | tokens never stop working |
| not before | nbf | a token is usable before it should be |
The two in bold are the ones people skip, and both have caused real breaches. A signature says somebody with a key signed this. It does not say the key was yours or this token was meant for this service. If two of your services trust the same issuer, a token for the low-privilege one is a perfectly valid signature at the high-privilege one — unless aud is checked.
Configuring a resource server
Spring does the validation for you, and the configuration is deliberately small:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.comThat one line makes Spring fetch the issuer's OpenID configuration, find the JWK Set endpoint, download the public keys, and validate signature, issuer and expiry on every request. Audience is not checked by default — you add it:
@Bean JwtDecoder jwtDecoder(OAuth2ResourceServerProperties props) {
NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation(props.getJwt().getIssuerUri());
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer(props.getJwt().getIssuerUri()),
new JwtClaimValidator<List<String>>("aud", a -> a != null && a.contains("orders-api"))));
return decoder;
}With asymmetric keys — RS256, which is what an identity provider will use — your service only ever holds the public key. It can verify tokens and cannot mint them, which is exactly the property you want in a service that might be compromised.
Key rotation then costs nothing: the provider publishes a new key at the JWK Set URL with a new kid, tokens carry the kid they were signed with, and Spring fetches and caches what it needs. Nothing is deployed on your side.
Claims are not authorities until you map them
By default Spring turns a scope or scp claim into authorities prefixed SCOPE_. Your token probably has roles somewhere else, so you map them:
@Bean JwtAuthenticationConverter converter() {
JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthorityPrefix("ROLE_");
authorities.setAuthoritiesClaimName("roles");
JwtAuthenticationConverter c = new JwtAuthenticationConverter();
c.setJwtGrantedAuthoritiesConverter(authorities);
return c;
}Get the prefix wrong and hasRole("ADMIN") silently never matches — the same ROLE_ trap as the filter chain lesson, arriving from a different direction.
The costs you are accepting
Everything the sessions lesson said about statelessness applies here, concretely:
- No revocation. A token is valid until
expwhatever happens to the user's account. Keep access tokens short — 5 to 15 minutes — and put revocation on the refresh token, which lives server-side. - Stale claims.
roles: ["ADMIN"]keeps asserting that after the role is removed, for the life of the token. Anything that must be current is read at request time, not taken from the token. - A blocklist gives revocation back and takes statelessness away. It is a store lookup on every request. Sometimes right; it should be a decision.
Under the hood: fetching and caching a JWK Set, and how kid picks the right key
issuer-uri doing "the rest" in one line of properties is really a small sequence of real HTTP calls the first time your service needs to validate a token, and it is worth seeing them separately because each one is a place a misconfiguration shows up as a confusing failure rather than an obvious one. First, Spring fetches <issuer-uri>/.well-known/openid-configuration (or the OAuth 2.0 equivalent), a JSON document the authorization server publishes that lists its endpoints — token, authorization, userinfo, and critically jwks_uri. Second, it fetches that jwks_uri, which returns a JWK Set (RFC 7517): a JSON document with a keys array, each entry a public key in JWK form, carrying at minimum a key type (kty, e.g. RSA), the key material itself, and a kid — a key id the authorization server chose when it generated that key pair. A resource server that validates tokens it never issued has no other way to obtain the right public key; it was never told one out of band, it discovers the whole set from this one URL.
A token's JOSE header carries the kid of the key that signed it — visible in the same base64url-decoded header the previous lesson already showed for alg, right alongside it: {"alg":"RS256","kid":"2024-03-a","typ":"JWT"}. Validating a specific token is then a lookup, not a guess: take the kid from the token's header, find the JWK in the cached set whose own kid matches, and use that key's material to verify the signature — never the first key in the set, never "whatever key we have," because an authorization server that rotates keys will have more than one valid key published at once, precisely so that tokens signed just before a rotation still verify against the old key while new tokens verify against the new one. This is exactly what makes rotation cost the resource server nothing: the provider publishes a new JWK Set entry with a new kid, starts signing new tokens with it, and every already-issued token — still carrying the old kid in its header — keeps validating against the old entry for as long as that entry stays in the published set. Nothing on your side is redeployed, because nothing on your side hard-coded a key; the kid in the header is what routes each verification to the right entry.
The fetch itself is cached, not repeated per request — Spring's NimbusJwtDecoder (built via JwtDecoders.fromIssuerLocation or the equivalent) keeps the JWK Set in memory and only re-fetches on cache expiry or, in some configurations, on encountering a kid it does not currently recognise, which is the practical case that matters: if the authorization server rotates keys and a token arrives signed with a kid your cached set has not seen yet, a decoder that only trusts its stale cache would wrongly reject a token that is perfectly valid. That is the operational reason JWK Set caching has to account for rotation as a normal event rather than an outage, and why an authorization server keeps a just-retired key's JWK entry published for some overlap window after it stops signing with it — long enough that every resource server's cache has a chance to catch up before the old key disappears from the set entirely.
Try it yourself
Work out which cached key a rotated-in token actually verifies against
A resource server's cached JWK Set has two entries: kid: "2024-01" and kid: "2024-02", both currently valid on the authorization server. A request arrives carrying a JWT whose header is {"alg":"RS256","kid":"2024-02","typ":"JWT"}.
Before reading on: which cached JWK does the resource server use to verify this token's signature, and what would happen if the cache only held kid: "2024-01"?
The `kid` in the header selects the entry; a missing one is treated as unverifiable, not skipped
The resource server reads kid: "2024-02" from the token's own header and looks up the JWK Set entry with that exact kid — "2024-02" — using only that entry's public key material to verify the signature. It does not try every cached key hoping one works, and it does not fall back to "2024-01" just because that entry happens to be present; a JWK's kid is an identifier, not a suggestion, precisely because two different keys can both be validly signing tokens at once during a rotation window. If the cache held only "2024-01" — say, because the resource server fetched the JWK Set before the authorization server published "2024-02" — a well-behaved decoder re-fetches the JWK Set on encountering an unrecognised kid rather than immediately rejecting; only if the re-fetch still does not produce a "2024-02" entry (the authorization server truly does not have it, or the fetch fails) does verification fail. That distinction — an unrecognised kid triggering a re-fetch rather than an automatic rejection — is what lets key rotation happen without every resource server needing to be redeployed or restarted in lockstep with the authorization server's rotation schedule.
Misconceptions
- "The resource server needs to trust the authorization server's TLS certificate once, and that's the whole trust chain." TLS on the
jwks_urifetch protects that one HTTP call from tampering in transit; it says nothing about which specific key inside the fetched JWK Set should verify a specific token. That's a separate step — matching the token's ownkidto the right entry — and skipping it (using "the first key" or "any key that verifies") is exactly the kind of shortcut that quietly works during testing, with one key in the set, and breaks the moment a second one is rotated in. - "Rotating keys means old tokens stop working immediately, so it's a safe way to force logout." The opposite: rotation is designed to be non-disruptive. A token signed before rotation keeps its old
kidand keeps validating against the old JWK entry for as long as the authorization server keeps publishing it — which is deliberate, so in-flight tokens don't all fail at once. Forcing immediate invalidation of already-issued tokens is a revocation problem, not a rotation one, and rotation alone does not solve it.
Sources
- RFC 7517 — JSON Web Key (JWK).
- RFC 7515 — JSON Web Signature (JWS), header parameters including
kid. - OpenID Connect Discovery 1.0 (the
.well-known/openid-configurationdocument andjwks_uri). - Spring Security Reference — OAuth 2.0 Resource Server, JWT (
issuer-uri,NimbusJwtDecoder).