9

I've been using ReactiveAuthenticationManager in Spring Security + Webflux. It is customised to return an instance of UsernamePasswordAuthenticationToken which from what I can tell is an what I should be receiving when I call ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block(). As as far as I can tell I am unable to access the authentication context through both:

SecurityContextHolder.getContext().getAuthentication();

or

ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block()

And attempting to access those from controllers or components resolves to null. I had some doubts about whether I am really returning an Authentication instance in my custom manager and it seems like I am:

@Override
public Mono<Authentication> authenticate(final Authentication authentication) {
    if (authentication instanceof PreAuthentication) {
        return Mono.just(authentication)
            .publishOn(Schedulers.parallel())
            .switchIfEmpty(Mono.defer(this::throwCredentialError))
            .cast(PreAuthentication.class)
            .flatMap(this::authenticatePayload)
            .publishOn(Schedulers.parallel())
            .onErrorResume(e -> throwCredentialError())
            .map(userDetails -> new AuthenticationToken(userDetails, userDetails.getAuthorities()));
    }

    return Mono.empty();
}

Where PreAuthentication is an instance of a AbstractAuthenticationToken and AuthenticationToken extends UsernamePasswordAuthenticationToken

Interestingly although ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block() does not work in a controller I can inject the authentication principal with the @AuthenticationPrincipal annotation as a method parameter successfully in a controller.

This seems like a configuration issue but I cannot tell where. Anyone have any idea why I cannot return authentication?

a better oliver
  • 26,330
  • 2
  • 58
  • 66
DWB
  • 1,544
  • 2
  • 16
  • 33

5 Answers5

23

Since you are using WebFlux, you are handling requests using event-loop. You are not using thread-per-request model anymore, as with Tomcat.

Authentication is stored per context.

With Tomcat, when request arrives, Spring stores authentication in SecurityContextHolder. SecurityContextHolder uses ThreadLocal variable to store authentication. Specific authentication object is visible to you, only if you are trying to fetch it from ThreadLocal object, in the same thread, in which it was set. Thats why you could get authentication in controller via static call. ThreadLocal object knows what to return to you, because it knows your context - your thread.

With WebFlux, you could handle all requests using just 1 thread. Static call like this won't return expected results anymore:

SecurityContextHolder.getContext().getAuthentication();

Because there is no way to use ThreadLocal objects anymore. The only way to get Authentication for you, is to ask for it in controller's method signature, or...

Return a reactive-chain from method, that is making a ReactiveSecurityContextHolder.getContext() call.

Since you are returning a chain of reactive operators, Spring make a subscription to your chain, in order to execute it. When Spring does it, it provides a security context to whole chain. Thus every call ReactiveSecurityContextHolder.getContext() inside this chain, will return expected data.

Your can read more about Mono/Flux context here, because it is a Reactor-specific feature.

Alex Derkach
  • 741
  • 5
  • 8
5

I also had a similar problem. so, I uploaded my github for ReactiveSecurityContext with JWT Token example.

https://github.com/heesuk-ahn/spring-webflux-jwt-auth-example

I hope it helps for you.

We need to create a custom authentication filter. If authentication succeeds in that filter, then it stores the principal information in the ReactiveSecurityHolder. We can access the ReactiveSecurityHolder from the controller.

ahn heesuk
  • 101
  • 2
  • 4
1

In addition to what Alex Derkach said, in more simple terms:

ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block()

will yield null, because you are disrupting the reactor chain.

What you can do is return the Mono object directly inside the RestController Then you will see the authentication context is indeed present.

0

Today resolved such problem in the next way:

Authentication authentication = new UserPasswordAuthenticationToken(userCredentials, null, userCredentials.getAuthorities());

ReactiveSecurityContextHolder.getContext()
.map(context -> context.getAuthentication().getPrincipal())
.cast(UserCredentials.class)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.subscribe();

UserCredential.class - is custom class, which contains userId, initials, login and authorities.

Kirill Parfenov
  • 445
  • 5
  • 7
-2

If you want to access the authentication object inside a webfilter, you can do it like this.

@Override
  public Mono<Void> filter(ServerWebExchange exchange, @NotNull WebFilterChain chain) {
    return exchange.getSession().flatMap((session) -> {
      SecurityContext context = session.getAttribute(SPRING_SECURITY_CONTEXT_ATTR_NAME);
      logger.debug((context != null)
              ? LogMessage.format("Found SecurityContext '%s' in WebSession: '%s'", context, session)
              : LogMessage.format("No SecurityContext found in WebSession: '%s'", session));
      if(context == null){
        return filterHelper(exchange, chain);
      }else{
        // access the principal object here 
      }

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 13 '22 at 08:37