oauth2ResourceServer() enables OAuth 2 or OpenID Connect resource-server authentication on an HttpSecurity configuration. Choose JWT validation when the resource server can verify token signatures locally, or opaque-token introspection when it must ask the authorization server about validity and token details. section 15.5
Configure the method according to the access-token format:
- For JWTs, call jwt() and configure jwkSetUri() with the authorization server's public key set URI. The resource server retrieves public keys and validates token signatures. section 15.1 section 15.5
- For opaque tokens, call opaqueToken(), configure introspectionUri(), and provide the resource server's client credentials for authorization-server requests. section 15.3 section 15.5
- Protect endpoints separately with authorizeHttpRequests(), because endpoints are not protected by default in the demonstrated configuration. section 15.1 section 15.3
JWT resource-server configuration
A SecurityFilterChain can inject a configured key-set URI, select JWT authentication, and require authentication for every request: http.oauth2ResourceServer(c -> c.jwt(j -> j.jwkSetUri(keySetUri))); http.authorizeHttpRequests(c -> c.anyRequest().authenticated());
Listing 15.5 Configuring the authentication with JWTs
@Configuration
public class ProjectConfig {
@Value("${keySetURI}")
private String keySetUri;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.oauth2ResourceServer( #1
c -> c.jwt( #2
j -> j.jwkSetUri(keySetUri) #3
)
);
return http.build();
}
}
Annotated Java configuration shows the nested oauth2ResourceServer(), jwt(), and jwkSetUri() customizers. section 15.1
Listing 15.15 Configuring the resource server authentication for opaque tokens
@Configuration
public class ProjectConfig {
@Value("${introspectionUri}")
private String introspectionUri;
@Value("${resourceserver.clientID}")
private String resourceServerClientID;
@Value("${resourceserver.secret}")
private String resourceServerSecret;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.oauth2ResourceServer(
c -> c.opaqueToken( #1
o -> o.introspectionUri(introspectionUri) #2
.introspectionClientCredentials( #3
resourceServerClientID,
resourceServerSecret)
)
);
return http.build();
}
}
Annotated Java configuration shows opaqueToken(), introspectionUri(), and introspectionClientCredentials(). section 15.3
Reactive applications use the same oauth2ResourceServer() and jwt() pattern with ServerHttpSecurity and SecurityWebFilterChain; the demonstrated variant validates signatures through a key-set URI. section 17.4
