Sub topic 10
Protecting the API with JWT bearer tokens
This chapter assumes you can write a SecurityFilterChain bean, know how stateless sessions work, and understand role and authority rules for HTTP requests. Here you will turn the API into an OAuth2 resource server that accepts JWT bearer tokens.
The working model
A resource server is an API that does not log users in. A separate authorization server, such as Keycloak, authenticates the user and issues a token. The client then sends that token on every request:
Authorization: Bearer eyJhbGciOi...A JWT (JSON Web Token) is a signed string with three parts: a header, a set of claims (key-value facts such as sub, iss, exp and scope), and a signature. The API checks the signature with the issuer's public key, so it needs no session and no password lookup. This is why JWTs fit stateless APIs.
Configuring the filter chain
Add the spring-boot-starter-oauth2-resource-server dependency. Then replace httpBasic with oauth2ResourceServer:
@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();
}Tell Spring Boot where the issuer lives:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.com/realms/demoAt startup, Spring Boot contacts the issuer's discovery endpoint, finds the key set, and builds a JwtDecoder. That decoder verifies the signature, the expiry time (exp) and the issuer (iss).
From claims to authorities
After validation, Spring Security converts the token into an Authentication object and stores it in the SecurityContext. The default converter reads the scope (or scp) claim and turns each value into an authority with the prefix SCOPE_. A token with "scope": "orders.read profile" yields SCOPE_orders.read and SCOPE_profile. This is why the rule above uses hasAuthority("SCOPE_orders.read") and not hasRole.
Common errors
| Symptom | Likely cause |
|---|---|
| 401 on every request | The token is expired, the `iss` claim differs from `issuer-uri`, or the header is not `Bearer <token>`. |
| 403 with a valid token | The token lacks the required scope, or the rule uses `hasRole` where the token carries `SCOPE_` authorities. |
| Application fails at startup | The issuer is unreachable when the decoder is built from `issuer-uri`. |
| Tokens accepted by the wrong API | The `aud` (audience) claim is not checked. Add an audience validator to the `JwtDecoder`. |
Distinguishing 401 from 403
A missing, malformed or invalid token produces 401 with a WWW-Authenticate: Bearer header. A valid token that lacks the needed authority produces 403. The test in the later testing chapter relies on this difference.
Exercise
A client sends a valid, unexpired JWT whose scope claim is orders.write. The API requires hasAuthority("SCOPE_orders.read") for GET /api/orders. What status code does the client get, and why?
Show answer
403 Forbidden. The token is valid, so authentication succeeds and no 401 is returned. The converter produces the authority SCOPE_orders.write, which does not match SCOPE_orders.read, so authorization fails.
Exercise
Your issuer stores user roles in a claim named roles, and hasRole("ADMIN") never matches. What do you change?
Show answer
Register a JwtAuthenticationConverter with a JwtGrantedAuthoritiesConverter that reads the roles claim and uses the authority prefix ROLE_. Then pass it with oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(converter)).