Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveSecurityContextHolder is empty in Spring WebFlux

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...

like image 587
Jul13nT Avatar asked Jun 18 '18 08:06

Jul13nT


1 Answers

You have to return the stream in which you want to access ReactiveSecurityContextHolder. You're not allowed to subscribe within another stream OR you have to do the Reactor context switch manually.

@Component
class Handler {
    Mono<ServerResponse> all(ServerRequest request) {
        return ReactiveSecurityContextHolder.getContext()
                .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getName)
                .flatMap(s -> Mono.just("Hi " + s))
                .doOnNext(System.out::println)
                .doOnError(Throwable::printStackTrace)
                .doOnSuccess(s -> System.out.println("completed without value: " + s))
                .flatMap(s -> ServerResponse.ok().build());
    }
}
like image 168
xtermi2 Avatar answered Oct 14 '22 07:10

xtermi2