Sub topic 10
Protecting the API with JWT bearer tokens
This chapter assumes you have a working SecurityFilterChain bean, understand stateless sessions, and know how authorizeHttpRequests matches paths. It shows how to make your API accept JSON Web Tokens (JWTs) issued by a separate authorization server, and how to validate and map them.
What a bearer token changes
With HTTP Basic, the client sends a username and password on every request, and your API checks them against a UserDetailsService. With bearer tokens, a separate authorization server (Keycloak, Auth0, Okta, Spring Authorization Server) authenticates the user and issues a signed token. The client sends it like this:
GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6...Your API is then a resource server. It never sees the password and never issues tokens. It only does three things:
- Extracts the token from the
Authorizationheader. - Verifies the signature and the standard claims.
- Turns the claims into an
Authenticationwith authorities.
A JWT has three Base64URL-encoded parts separated by dots: a header (algorithm and key id), a payload of claims, and a signature. Anyone can read the payload, so never put secrets in it. Only the signature proves it was not altered.
Add the dependency
The resource-server support lives in its own starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>Configure the filter chain
Replace httpBasic with oauth2ResourceServer. Keep the stateless policy and disable CSRF, since there is no session cookie to forge.
@Bean
SecurityFilterChain resourceServer(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAuthority("SCOPE_orders.read")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}Then tell Spring Boot who issues the tokens:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.com/realms/demoHow validation works
With only the issuer URI configured, Spring Boot builds a JwtDecoder that does the following:
- Fetches the issuer's metadata from its well-known discovery endpoint and finds the
jwks_uri, the location of the public signing keys. - Downloads the JSON Web Key Set (JWKS) and caches it. It selects the key whose id matches the token's
kidheader. - Verifies the signature.
- Checks that
exp(expiry) has not passed, thatnbf(not before) has been reached if present, and thatissequals the issuer URI.
The decoder fetches the issuer metadata lazily, on the first request that carries a token. If the authorization server is down at that moment, the request fails and the decoder retries on a later request.
The request itself passes through BearerTokenAuthenticationFilter, which sits in the same filter chain you learned earlier.
From claims to authorities
Authorization rules need GrantedAuthority objects, not raw claims. By default, a JwtGrantedAuthoritiesConverter reads the scope claim (a space-separated string) or the scp claim (a list) and prefixes each value with SCOPE_.
| Token claim | Resulting authority | Matches |
|---|---|---|
| `"scope": "orders.read orders.write"` | `SCOPE_orders.read`, `SCOPE_orders.write` | `hasAuthority("SCOPE_orders.read")` |
| `"scp": ["profile"]` | `SCOPE_profile` | `hasAuthority("SCOPE_profile")` |
| `"roles": ["ADMIN"]` | none by default | needs a custom converter |
Note that hasRole("ADMIN") looks for ROLE_ADMIN, so it never matches a scope. Use hasAuthority for scopes and hasRole only after you map a role claim.
Mapping a roles claim
Many providers put roles in a custom claim such as roles. Configure a JwtAuthenticationConverter to read it:
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
var authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("roles");
authorities.setAuthorityPrefix("ROLE_");
var converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
return converter;
}Register it in the filter chain:
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))).requestMatchers("/api/admin/**").hasRole("ADMIN")This converter replaces the default one, so scopes are no longer mapped. If you need both scopes and roles, write a converter that combines two lists of authorities.
Reading the token in a controller
After authentication, the principal is a Jwt. Inject it with @AuthenticationPrincipal:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
class MeController {
@GetMapping("/api/me")
Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
return Map.of(
"subject", jwt.getSubject(),
"issuer", jwt.getIssuer().toString(),
"expires", jwt.getExpiresAt().toString());
}
}Use the sub claim as the stable user identifier. Usernames and emails can change.
Validating the audience
The issuer check proves who signed the token. It does not prove the token was meant for your API. A token issued for another API from the same authorization server would pass. The aud (audience) claim says who the token is for, and you must check it yourself with a custom validator:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
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;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtDecoders;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@Bean
JwtDecoder jwtDecoder(
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuer) {
var decoder = (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuer);
OAuth2TokenValidator<Jwt> audience = jwt -> jwt.getAudience().contains("orders-api")
? OAuth2TokenValidatorResult.success()
: OAuth2TokenValidatorResult.failure(
new OAuth2Error("invalid_token", "The required audience is missing", null));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer(issuer), audience));
return decoder;
}Defining your own JwtDecoder bean makes Spring Boot back off from its auto-configured one. JwtDecoders.fromIssuerLocation contacts the issuer immediately, so the application fails at startup if the issuer is unreachable.
Common errors
- 401 on every request. The token is missing, expired, signed by a different issuer, or the
Authorizationvalue does not start withBearer(with a space). The response carries aWWW-Authenticate: Bearer error="invalid_token"header that names the cause. - 403 with a valid token. Authentication succeeded, but the required authority is not in the token. Decode the token and compare its
scopeclaim with the rule. Remember theSCOPE_prefix. hasRolenever matches. Scopes do not become roles. Map a roles claim or switch tohasAuthority.- Startup failure or first-request failure around the issuer. The API cannot reach the
issuer-uri. In containers, check DNS and network rules. If theissclaim differs from the URI (for examplehttpversushttps, or a trailing slash), validation fails. - Clock skew. The default validator allows 60 seconds of drift on
expandnbf. Larger gaps between servers produce intermittent 401 responses. - Expecting logout to work. A self-contained JWT stays valid until
exp. Keep access tokens short-lived, usually 5 to 15 minutes, and let clients refresh them with the authorization server.
Opaque tokens as an alternative
Some authorization servers issue opaque tokens, which are random strings with no readable claims. Spring Security supports them through oauth2ResourceServer(o -> o.opaqueToken(...)), which calls the server's introspection endpoint on each request. This allows instant revocation but adds a network call per request. JWTs avoid that call at the cost of slower revocation.
Exercise
A client sends a correctly signed, unexpired JWT from your trusted issuer with "scope": "orders.write" to GET /api/orders, which requires hasAuthority("SCOPE_orders.read"). What status does it receive and why? What status would it receive if it sent no Authorization header?
Show answer
It receives 403. The token passes validation, so the request is authenticated, but the resulting authorities contain only SCOPE_orders.write, so the authorization check fails. With no Authorization header the request is anonymous and the entry point responds with 401 and a WWW-Authenticate: Bearer header.
Exercise
Your tokens carry the user's roles in a claim named roles, for example ["ADMIN"]. Your rule is .requestMatchers("/api/admin/**").hasRole("ADMIN"), but admins get 403. What change fixes it?
Show answer
Register a JwtAuthenticationConverter whose JwtGrantedAuthoritiesConverter uses setAuthoritiesClaimName("roles") and setAuthorityPrefix("ROLE_"), and attach it with jwt.jwtAuthenticationConverter(...). The default converter reads only scope and scp, so ROLE_ADMIN was never granted.