I am trying to use the ReactiveSecurityContextHolder with Spring WebFlux. Unfortunately, the SecurityContext is empty :
@Configuration
public class Router {
@Bean
public RouterFunction<ServerResponse> routes(Handler handler) {
return nest(
path("/bill"),
route(
GET("/").and(accept(APPLICATION_JSON)), handler::all));
}
@Component
class Handler {
Mono<ServerResponse> all(ServerRequest request) {
ReactiveSecurityContextHolder.getContext()
.switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
.map(SecurityContext::getAuthentication)
.map(Authentication::getName)
.flatMap(s -> Mono.just("Hi " + s))
.subscribe(
System.out::println,
Throwable::printStackTrace,
() -> System.out.println("completed without a value")
);
return ok().build();
}
}
}
This code always throws the IllegalStateException.
If I add a subscriberContext like shown here :
Authentication authentication = new TestingAuthenticationToken("admin", "password", "ROLE_ADMIN");
ReactiveSecurityContextHolder.getContext()
.switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
.map(SecurityContext::getAuthentication)
.map(Authentication::getName)
.flatMap(s -> Mono.just("Hi " + s))
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
.subscribe(
System.out::println,
Throwable::printStackTrace,
() -> System.out.println("completed without a value")
);
It works fine and print "Hi admin". But that's not the point, the article says "In a WebFlux application the subscriberContext
is automatically setup using ReactorContextWebFilter
". So I should be able to fetch the logged user.
I have this configuration :
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.anyExchange().authenticated()
.and().formLogin()
.and().build();
}
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build();
return new MapReactiveUserDetailsService(user, admin);
}
}
Am I missing something here ? If I put breakpoints in ReactorContextWebFilter, I can see that it is correctly called before each request. But my ReactiveSecurityContextHolder is always empty...