I'm developing an application where my back-end is a stateless resource server. Every request that it receives should contain an Authentication
header with a JWT Bearer token - currently a Google id_token
. I'm able to verify the token, but in order to achieve method level security I need to be able to set the principal's role and name with information from a repository/service. How can I set the role and name of the principal?
Following the Spring tutorial, I'm trying to define a UserDetailsService
bean to set the information, but it doesn't seem to be invoked. I've added a breakpoint in the findByUsername
method but the execution never stops there.
application.yml file
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://accounts.google.com
Config.java file:
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) throws Exception {
http
.authorizeExchange()
.pathMatchers("/**")
.authenticated()
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
// Using MapReactiveUserDetailsService, but I'll create my custom UserDetailsService implementation
@Bean
public MapReactiveUserDetailsService userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails rob = userBuilder.username("rob") //Instead of 'rob' and 'admin' I have in my code the Google ID of the Google accounts that I'm using to create the token
.password("rob")
.roles("USER")
.build();
UserDetails admin = userBuilder.username("admin")
.password("admin")
.roles("USER","ADMIN")
.build();
return new MapReactiveUserDetailsService(rob, admin);
}
SecuredController.java file:
@RestController
public class SecuredController {
@GetMapping("/secured")
@PreAuthorize("hasRole('ADMIN')")
public Mono<Principal> secured(Principal principal) {
return Mono.just(principal);
}
}
With this configuration the user details service is not being called and I can't reach the GET /secured
endpoint. I would like to reach it using the user with ADMIN role.