DWB
DWB

Reputation: 1554

ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works

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?

Upvotes: 9

Views: 19624

Answers (5)

Michalis Marolachakis
Michalis Marolachakis

Reputation: 46

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.

Upvotes: 1

Pratik Singh
Pratik Singh

Reputation: 27

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 
      }

Upvotes: -2

Kirill Parfenov
Kirill Parfenov

Reputation: 653

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.

Upvotes: 0

henry
henry

Reputation: 111

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.

Upvotes: 5

Alex Derkach
Alex Derkach

Reputation: 759

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.

Upvotes: 23

Related Questions