How to get current user from ReactiveSecurityContextHolder in WebFlux?

Viewed 2156

Usually while working with Spring Boot, a common way to get currently logged users is to use:

SecurityContextHolder.getContext();

This does not work when working with reactive programming, and Mono in Java since they do not belong to the same thread. It's recommended to use:

ReactiveSecurityContextHolder.getContext()

I've read many articles, StackOverflow questions, and answers, but never found a full explanation or example of how to fully integrate ReactiveSecurityContextHolder.

Any help would be highly appreciated.

This is what I have tried:

   @RequestMapping(value = "/get-auth", method = RequestMethod.GET)
public @ResponseBody Mono<Authentication> test(Authentication authp) {
    return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).doOnNext(auth -> {
        log.info("print auth", String.valueOf(auth));
    }).doOnSuccess(auth -> {
        log.error("print auth", auth);
    });
}

doOnSuccess - returns null
doOnNext - not triggered

1 Answers

Assuming security is configured correctly. Spring security initialize ReactiveSecurityContextHolder during subscription so you can access it within this chain using ReactiveSecurityContextHolder.getContext():

@GetMapping
Mono<Void> getItems() {
    return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .doOnNext(auth -> log.info(String.valueOf(auth)))
            .then();
}

Sample output:

UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=admin, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_ADMIN]]

Related