0

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

2
  • 1
    Does this answer your question? How to get spring security context in reactive webflux. subscribe is not synchronous operation and your request ends before subscription happen. Instead of subscribing explicitly - return Mono from your controller Commented Feb 18, 2023 at 18:42
  • My actual requirement is access Authentication object and perform validation on the principal it contains. I am struggling to access Authentication. I thought I can read Authentication through subscription approach but it was not helpful for the reasons you specified. Commented Feb 19, 2023 at 2:35

1 Answer 1

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.