Search code examples
javaspring-securityspring-webflux

Mono does not emit value when subscribed


I am trying to validate authentication in reactive spring application with Spring Security. I could not read content from Mono in the controller. It is not emitting any values when I subscribed. I have the following code in the controller:

@Controller
public class TestConroller {

 public void test(){
   Mono<Authentication> monoAuth=ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
   monoAuth.subscribe(authentication->validate(authentication) 
 }
 private void validate(Authentication authentication){
   System.out.println(authentication.getPrincipal().getName());
 }
}

The validate method is never called


Solution

  • Although "nothing happens until you subscribe", you don't need to call subscribe explicitly. WebFlux will subscribe behind the scene if you return Mono<T>. You just need to build a flow combining different reactive operators.

    public Mono<String> test() {
            return ReactiveSecurityContextHolder.getContext()
                    .map(ctx -> validate(ctx.getAuthentication()));
        }
        
        private String validate(Authentication authentication){
            String name = ((Principal) authentication.getPrincipal()).getName();
    
            // validate
            return name;
        }