Sub topic 7
Configuring the JwtDecoder
This chapter assumes you have a working Spring Boot app with Spring Security on the classpath and the spring-boot-starter-oauth2-resource-server dependency. It also assumes you know what a JWT is and why the signature matters. Here you will see what the JwtDecoder does, how Boot builds one from properties, and how to build your own when the properties are not enough.
What the JwtDecoder does
JwtDecoder is the Spring Security interface that turns a raw bearer string into a Jwt object, or throws a JwtException. The resource server filter calls it once per request. The default implementation is NimbusJwtDecoder, which wraps the Nimbus JOSE library.
Decoding takes four steps:
- Parse the compact string into header, payload, and signature.
- Pick a verification key. The decoder matches the
kidandalgfrom the header against the provider's JWK set. - Verify the signature.
- Run the configured validators over the claims.
If any step fails, the request is rejected with a 401 (see the chapter on 401 and 403 responses).
Option 1: issuer-uri
The shortest configuration sets only the issuer:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com/realms/demoBoot then does the following:
- It requests the provider's metadata from
{issuer-uri}/.well-known/openid-configuration. It also tries the OAuth 2.0 authorization server metadata paths. - It reads
jwks_urifrom the metadata and uses that URL to fetch signing keys. - It checks that the
issuervalue in the metadata equals the configuredissuer-uri. - It adds a validator that requires each token's
issclaim to match.
The discovery request happens lazily, on the first request that needs a decoder. Boot wraps the decoder so that the application starts even when the provider is down. The first protected request then fails, and later requests retry.
The issuer-uri value must match the iss claim exactly, including any trailing slash. A mismatch is the most common cause of a 401 on a token that looks fine.
Option 2: jwk-set-uri
If the provider has no discovery endpoint, or you want to avoid the discovery call, point directly at the key set:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://issuer.example.com/realms/demo/protocol/openid-connect/certs
jws-algorithms: RS256With only jwk-set-uri, the decoder verifies signatures and checks exp and nbf. It does not check iss. You can set both properties. Boot then fetches keys from jwk-set-uri, skips discovery, and adds the issuer check from issuer-uri.
| Properties set | Keys come from | Issuer checked | Discovery call |
|---|---|---|---|
| `issuer-uri` only | `jwks_uri` in metadata | Yes | Yes |
| `jwk-set-uri` only | `jwk-set-uri` | No | No |
| Both | `jwk-set-uri` | Yes | No |
The algorithm setting
By default the decoder accepts only RS256. If your provider signs with another algorithm, set jws-algorithms, for example jws-algorithms: ES256. If you leave the default, valid tokens are rejected with a message like "Another algorithm expected, or no matching key(s) found".
The decoder only accepts algorithms you list, and it does not read the choice from the token header. This blocks attacks where a forged token declares alg: none or switches from an asymmetric to a symmetric algorithm. Keep the list as short as your provider allows.
Building the decoder yourself
Declare a JwtDecoder bean when you need to customize validation, HTTP behavior, or key sources. Boot's auto-configured decoder is conditional on there being no JwtDecoder bean, so yours replaces it completely. Properties such as jws-algorithms stop applying unless you read them yourself.
The NimbusJwtDecoder builders cover the common key sources:
| Builder | Use when |
|---|---|
| `withIssuerLocation(issuer)` | You want discovery. It makes a network call when `build()` runs. |
| `withJwkSetUri(uri)` | You know the JWK set URL. |
| `withPublicKey(rsaPublicKey)` | You have one fixed RSA public key and no JWK set. |
| `withSecretKey(secretKey)` | Tokens use HMAC. This is rare for third-party providers. |
A decoder built from a JWK set URL with an explicit algorithm looks like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@Configuration
public class DecoderConfig {
private static final String ISSUER = "https://issuer.example.com/realms/demo";
private static final String JWKS =
"https://issuer.example.com/realms/demo/protocol/openid-connect/certs";
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(JWKS)
.jwsAlgorithm(SignatureAlgorithm.ES256)
.build();
OAuth2TokenValidator<Jwt> validator = JwtValidators.createDefaultWithIssuer(ISSUER);
decoder.setJwtValidator(validator);
return decoder;
}
}JwtValidators.createDefaultWithIssuer(...) combines the timestamp and issuer checks. In practice, read ISSUER and JWKS from properties with @Value instead of constants.
Why validators need care
setJwtValidator replaces the existing validator. It does not add to it. A decoder you build yourself starts with only the timestamp check. If you call setJwtValidator with a single custom validator, you drop the timestamp check unless you include it again.
When you add checks such as audience, wrap them in a DelegatingOAuth2TokenValidator together with the defaults. The next chapter shows that pattern in detail. For now, remember the rule: whatever you pass to setJwtValidator is the complete list of checks.
HTTP behavior and key fetching
The decoder fetches the JWK set over HTTP. Nimbus caches the keys and refetches when a token carries a kid it does not know. This is how key rotation works in practice, and a later chapter covers it.
The default HTTP client has short built-in timeouts, but you may want to set your own, or route requests through a proxy. Pass a RestOperations to the builder:
import java.time.Duration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;
@Bean
JwtDecoder jwtDecoder(RestTemplateBuilder builder,
@Value("${app.jwks-uri}") String jwksUri) {
RestTemplate rest = builder
.setConnectTimeout(Duration.ofSeconds(2))
.setReadTimeout(Duration.ofSeconds(2))
.build();
return NimbusJwtDecoder.withJwkSetUri(jwksUri)
.restOperations(rest)
.build();
}Timeouts matter because the key fetch runs on the request thread. A slow provider with no timeout can tie up your request threads.
Common errors
- 401 with a valid-looking token, log says "iss claim is not valid". The token's
issdiffers fromissuer-uri. Check for a trailing slash or a hostname the provider sees differently, such aslocalhostin a container versus a public name. - 401, "Another algorithm expected, or no matching key(s) found". The token's
algis not injws-algorithms, or thekidis missing from the JWK set. Compare the token header with the JWK set. - Startup fails with an issuer error. You called
withIssuerLocationorJwtDecoders.fromIssuerLocationdirectly in a bean method. Those calls hit the network at startup. Useissuer-uriin properties, or usewithJwkSetUri, to get lazy behavior. - Tokens with an expired
expare accepted. You replaced the validator and dropped the timestamp check. - Clock skew. The default timestamp validator allows 60 seconds of skew. Larger differences between the provider's clock and yours cause intermittent 401s.
Exercise
Your provider signs tokens with ES256 and publishes no discovery document. You configure only jwk-set-uri. The signature check works, but a token from a different issuer with a valid signature from a shared key set is accepted. What two changes fix the problem, and what happens if you set only issuer-uri and nothing else?
Show answer
Add jws-algorithms: ES256 so the decoder accepts the right algorithm (the default is RS256 and would otherwise reject the real tokens). Also add issuer-uri, or call setJwtValidator(JwtValidators.createDefaultWithIssuer(issuer)) on a custom decoder, so the iss claim is checked. With jwk-set-uri alone, only the signature and timestamps are validated. If you set only issuer-uri, Boot tries discovery and takes the key location from jwks_uri, which fails here because the provider has no discovery document. Setting both properties avoids discovery and still checks the issuer.