Sub topic 2
Turning a Spring Boot App into a Resource Server
Assume you know basic Spring Boot configuration, HTTP headers, authentication, and authorization. A resource server protects an API and verifies access tokens before allowing requests to reach controllers.
Configure the Resource Server
Add Spring Security’s OAuth2 resource-server support. Then configure the token issuer:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com/realms/demoThe issuer-uri identifies the authorization server. Spring Boot uses its metadata to find the JSON Web Key Set (JWKS), which contains public keys for checking token signatures.
Configure a stateless filter chain:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
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();
}
}Configure and Validate the JwtDecoder
issuer-uri enables default validation of the issuer and time claims such as exp and nbf. If discovery is unavailable, use a direct key endpoint:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://issuer.example.com/.well-known/jwks.jsonAdd audience validation when tokens from the same issuer can target different APIs:
@Bean
JwtDecoder jwtDecoder(
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
String issuer) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
OAuth2TokenValidator<Jwt> defaults =
JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> audience =
new JwtClaimValidator<List<String>>(
"aud", aud -> aud != null && aud.contains("orders-api"));
decoder.setJwtValidator(
new DelegatingOAuth2TokenValidator<>(defaults, audience));
return decoder;
}The decoder rejects expired tokens, tokens not yet valid, tokens with the wrong iss, and tokens whose aud does not include orders-api.
Map Claims to Authorities
Spring Security maps a JWT scope or scp claim to authorities prefixed with SCOPE_. For a custom roles claim, configure a converter:
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter authorities =
new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("roles");
authorities.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
return converter;
}Attach it with oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter( jwtAuthenticationConverter())).
Exercise
Why should an API validate the audience claim even when the token issuer is trusted?
Show answer
The audience identifies the intended API. Without that check, a token issued for another API might be accepted here.