1 year ago

#364319

test-img

CptWasp

Extracting Principal data using ReactiveSecurityContextHolder

I have a Spring webflux microservice, with working OAuth authentication in place. I can access the Principal using the @AuthenticationPrincipal annotation in the controller method parameters:

@GetMapping("/user-info")
public @ResponseBody User getUserInfo(@AuthenticationPrincipal Principal principal) {
    return service.getMe(principal);
}

This works fine.

But what I want, is to access the Principal directly, using ReactiveSecurityContextHolder, using something like:

@Override
public Principal getLoggedUser() {
    Mono<Principal> authentication=
        ReactiveSecurityContextHolder.getContext().filter(context -> 
                Objects.nonNull(context.getAuthentication()))
            .map(context -> context.getAuthentication().getPrincipal())
            .cast(Principal.class);
    return authentication.share().block();
}

I need to block, because I need some Principal data to access a non reactive database, loading the corresponding User.

For some reason, the above snippet always returns null. I tried with

return authentication.toFuture().get();

and got the same result.

java

spring

spring-webflux

spring-security-oauth2

reactor

0 Answers

Your Answer

Accepted video resources