Sub topic 8
Validating issuer, audience, and expiry
This chapter covers what Spring Security checks on a JWT after the signature verifies, and how to add the checks it does not do by default. It assumes you have a working resource server (the SecurityFilterChain and issuer-uri setup from the earlier chapters), and that you know the registered claims iss, aud, exp, nbf, and iat.
Why a valid signature is not enough
A valid signature proves that the key holder issued the token. It does not prove the token is meant for your API, that it came from the issuer you trust, or that it is still current. The same authorization server often issues tokens for many APIs. Without further checks, a token minted for a billing API could be replayed against your orders API.
Validation therefore has two layers:
- Signature verification, done by the
JwtDecoderusing keys from the JWK set. - Claim validation, done by a list of
OAuth2TokenValidator<Jwt>objects.
If any validator reports an error, the decoder throws JwtValidationException. The filter turns that into a 401 response.
What you get by default
The default depends on how you configure the decoder.
| Configuration | Timestamp check | Issuer check | Audience check |
|---|---|---|---|
| `issuer-uri` property only | Yes | Yes | No |
| `jwk-set-uri` property only | Yes | No | No |
| `NimbusJwtDecoder.withJwkSetUri(...)` built by hand | Yes | No | No |
| `NimbusJwtDecoder.withIssuerLocation(...)` built by hand | Yes | Not unless you add it | No |
Two points in this table cause real bugs:
- With
jwk-set-urialone, Spring has no issuer to compare against. Any token signed by a key in that set is accepted regardless ofiss. - No configuration checks
audfor you. Audience validation is always something you add.
The issuer-uri property is the simplest way to get issuer validation:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com/realms/demoAt startup, Spring Boot fetches the provider's metadata from that URL, finds the JWK set location, and adds an issuer validator. The iss claim must equal the configured string exactly. A trailing slash difference, or http versus https, causes every token to be rejected.
Expiry and not-before
JwtTimestampValidator is part of the defaults. It compares the current time against exp and nbf:
- If
expis in the past, the token is rejected. - If
nbfis in the future, the token is rejected.
It allows a clock skew of 60 seconds by default. A token that expired 30 seconds ago still passes, which absorbs small clock differences between the authorization server and your API. If you need a different tolerance, build the validator yourself:
OAuth2TokenValidator<Jwt> timestamps =
new JwtTimestampValidator(Duration.ofSeconds(10));Keep the skew small. A larger skew extends the life of every token by the same amount. Synchronize your servers with NTP rather than raising it.
The validator does not require exp to be present. A token with no exp never expires as far as this validator is concerned. If your policy says every token must expire, add a check for it, as shown below.
Adding audience validation
The aud claim names the APIs a token is intended for. In the JSON payload it may be a string or an array, but Spring's Jwt exposes it as a List<String>. The decoder below keeps the default timestamp and issuer checks and adds an audience check:
@Bean
JwtDecoder jwtDecoder(
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuer) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> withAudience = new JwtClaimValidator<List<String>>(
"aud", aud -> aud != null && aud.contains("orders-api"));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(withIssuer, withAudience));
return decoder;
}Reading it from the inside out:
JwtValidators.createDefaultWithIssuer(issuer)returns a delegating validator that holdsJwtTimestampValidatorandJwtIssuerValidator.JwtClaimValidatorreads one claim and applies a predicate. If the predicate returnsfalse, validation fails with aninvalid_tokenerror.DelegatingOAuth2TokenValidatorruns all validators and collects every error, not just the first.
When you define your own JwtDecoder bean, Spring Boot's auto-configured decoder backs off. Your bean is the only source of validation rules, so if you drop withIssuer you lose the issuer check.
Writing a reusable audience validator
A predicate in a lambda is fine for one rule. For a rule you will test or reuse, implement the interface. This version also returns a descriptive error:
import java.util.List;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private final String audience;
public AudienceValidator(String audience) {
this.audience = audience;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
List<String> aud = jwt.getAudience();
if (aud != null && aud.contains(audience)) {
return OAuth2TokenValidatorResult.success();
}
OAuth2Error error = new OAuth2Error(
"invalid_token", "The required audience is missing", null);
return OAuth2TokenValidatorResult.failure(error);
}
}Jwt.getAudience() returns null when the claim is absent, so the null check matters. Use it in the decoder with new DelegatingOAuth2TokenValidator<>(withIssuer, new AudienceValidator("orders-api")).
Requiring `exp`
The same pattern covers other policies. This validator rejects tokens that carry no expiry:
OAuth2TokenValidator<Jwt> requireExpiry = new JwtClaimValidator<Object>(
"exp", Objects::nonNull);Which claim value does the audience hold?
Not every authorization server puts your API name in aud. Some use a client ID, a URL, or a resource identifier you register. Others, including some that issue access tokens in a Keycloak-style layout, put the intended API in a different claim and leave aud as account or similar. Decode a real token and check what it contains before you hard-code a value. Use the actual string, with exact case.
Edge cases and failure modes
- Wrong issuer string. Spring compares
isswith a plain string match. Copy the issuer from the provider's/.well-known/openid-configurationdocument, fieldissuer, rather than typing it. - Startup dependency. With
issuer-uri, the app contacts the provider on first use (lazily in current Spring Boot versions). If the provider is unreachable then, the first requests fail with401or500depending on the error. Usejwk-set-uriwith an explicit issuer validator if you need to avoid this lookup. - Multiple audiences.
containsaccepts a token that lists your API alongside others. That is usually acceptable. Useequalson a single-element list only if your policy forbids shared tokens. - ID tokens as bearer tokens. An OpenID Connect ID token is meant for the client, not your API. Its
audis the client ID, so audience validation rejects it. That is the desired behavior. - Validation order. Validators run after the signature check. Never trust claim values for any purpose before the decoder has finished.
Seeing the error
A token with the wrong audience produces a response like this:
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="The required audience is missing", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"The error_description comes from your OAuth2Error. Keep it short and non-revealing. Do not include the expected issuer or the token contents.
Exercise
Your API is configured with only jwk-set-uri. A colleague shows that a token with iss set to an unrelated issuer, signed with a key from that JWK set, is accepted. Why does this happen, and what are two ways to fix it? Also, what extra check is needed so that the token must be intended for orders-api?
Show answer
With jwk-set-uri only, Spring builds a decoder with the timestamp validator but no issuer validator, so iss is never compared. Fix it by setting issuer-uri (which adds the issuer check) or by building the NimbusJwtDecoder yourself and calling setJwtValidator with JwtValidators.createDefaultWithIssuer(issuer). To require the audience, add a JwtClaimValidator or a custom OAuth2TokenValidator<Jwt> that checks aud contains orders-api, and combine it with the default validator using DelegatingOAuth2TokenValidator.
Exercise
A token expired 20 seconds ago and is still accepted by your resource server, which uses the default validators. Why, and how do you make it fail?
Show answer
JwtTimestampValidator allows 60 seconds of clock skew by default, so a token that expired 20 seconds ago is still within tolerance. Build the validator with a smaller skew, for example new JwtTimestampValidator(Duration.ofSeconds(5)), and include it in a DelegatingOAuth2TokenValidator set on the decoder.