Sub topic 6
Turning a Spring Boot app into a resource server
This chapter assumes you know basic Spring Boot and Spring MVC, HTTP headers and status codes, and the difference between authentication and authorization. You need Java 17 or later and Maven or Gradle. Earlier chapters covered the OAuth2 roles and the shape of a JWT. Here you wire an API into that model.
What a resource server does
A resource server is the API that holds protected data. It does not log users in. It reads the bearer token from the Authorization header, checks it, and decides whether to serve the request. The authorization server issues the tokens. Your app only verifies them.
Step 1: add the dependency
Add the resource server starter. It brings in Spring Security and the JOSE libraries that parse and verify JWTs.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>Step 2: point Boot at the issuer
Set the issuer URI of your authorization server.
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com/realms/demoAt startup, Spring Boot uses this URI to discover the provider's metadata and its JWK set. The JWK set is the list of public keys used to verify signatures. Boot also validates the iss claim of incoming tokens against this value.
Discovery makes a network call to the issuer. If the issuer is unreachable at startup, the decoder is not built, because Boot resolves the metadata when it first needs it. Depending on your version, this can fail startup or the first request. If you cannot depend on the issuer being up, use jwk-set-uri instead, which skips discovery. The next chapter compares the two.
Step 3: define the filter chain
Boot's defaults protect every request, but you will usually want explicit rules. This chain is stateless, so no HTTP session is created. It requires a valid JWT everywhere except /public/**, and it requires the admin scope for /admin/**.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}The pieces do these jobs:
oauth2ResourceServer(...)adds the bearer token filter that extracts and authenticates the token.jwt(Customizer.withDefaults())selects JWT validation and uses theJwtDecoderthat Boot built from your properties.STATELESStells Spring Security not to create or use a session. Each request must carry its own token.SCOPE_adminis an authority name. By default, each value in the token'sscopeclaim becomes an authority with theSCOPE_prefix.@EnableMethodSecurityturns on annotations such as@PreAuthorize, which a later chapter uses.
Rule order matters. Spring Security checks the rules from top to bottom and uses the first match, so put specific matchers before anyRequest().
Step 4: read the caller in a controller
The validated token is available as a Jwt object.
@RestController
class OrderController {
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
return Map.of("sub", jwt.getSubject(), "issuer", jwt.getIssuer().toString());
}
}Call it with a token to check the setup:
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/meWithout the header you get 401 Unauthorized. With a valid token you get the sub and issuer values.
Common errors
- Startup or first-request failure about the issuer. The app could not reach the discovery endpoint. Check the URL, and check that it serves
/.well-known/openid-configurationbelow the issuer path. - 401 on every call with a valid-looking token. The token's
issdoes not matchissuer-uriexactly. A trailing slash is enough to break it. - 403 where you expected 200. The token authenticated, but lacks the authority. Check the
scopeclaim, and remember theSCOPE_prefix. - Session cookies appear. You left out
STATELESS.
Exercise
Your API returns 401 for tokens that decode correctly in a JWT debugger. The iss claim is https://issuer.example.com/realms/demo/, and your issuer-uri is https://issuer.example.com/realms/demo. What is the likely cause, and what do you change?
Show answer
The issuer check compares strings exactly, so the trailing slash makes the values differ and validation fails. Make issuer-uri match the token's iss claim exactly, or fix the authorization server so it issues the form you configured. Do not disable the issuer check.
Exercise
Why does the filter chain set SessionCreationPolicy.STATELESS, and what must each client request include as a result?
Show answer
A resource server authenticates every request from its token and keeps no login state, so no session should be created. Each request must carry its own Authorization: Bearer <token> header.