I'm using springboot v3.2.3 with the following dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
Here my config
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize -> authorize
.requestMatchers("swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}
I have this in applications.properties
spring.security.oauth2.resourceserver.jwt.issuer-uri=<issuer-uri>
spring.security.oauth2.resourceserver.jwt.audiences=<app>
The jwt token verification works correctly (by allowing only the specified audience and the application uses the right issuer public certificate ). However, I want to filter based on other claims, like roles. what's the cleanest way to do so ?
In my case the claim names are slightly different ! the scope is under
app_scopesclaim and the role is under theapp_rolesclaim, that's why SpringSecurity didn't map correctly theses claims with the authorities !Hence in order to configure the roles/scopes we have to use a custom jwt converter ( which converts the jwt token into an authentication object )
Then we just need to wire the JwtGrantedAuthoritiesConverter with our SpringSecurity configuration (FilterChain
Now we are able to manage the authorization ! The user's token should have SCOPE_super and ROLE_adminit to be able to access to the
/test-secured- endpointObviously we can also use
@PreAuthorizeat the method level.