0

I'm quite new to reactor and I've been stuck for too much time with the following code that doesn't work for me and I don't know what to do next.

I have simplified my code as follow :

@RestController
public class HelloController {

   @Autowired
   @Qualifier("currentUserService")
   private CurrentUserContextService userContextService;



   @GetMapping("/v1/hello2")
   public Mono<PulseUser> getHello2() {
       final Mono<PulseUser> currentUser2 = Mono
            .just(new PulseUser("login", "pasdsword", Collections.emptyList(), 65));

       currentUser2.subscribe(user -> {
          System.out.println("+++++++++" + user);
       });

       userContextService.getCurrentUser().subscribe(user -> {
           System.out.println("*************" + user);
       });

       return userContextService.getCurrentUser();
   }
}

with userContextService like this :

@Service("currentUserService")
public class CurrentUserContextServiceImpl implements CurrentUserContextService {

   @Override
   public Mono<PulseUser> getCurrentUser() {
    final Mono<SecurityContext> context = ReactiveSecurityContextHolder.getContext();
    return context.map(security -> {
        final PulseUser details = (PulseUser) security.getAuthentication().getDetails();
        return details;
    });

  }
}

With this, code, here what I get :

  • If I hit /v1/hello2, I get a json response with the current User : OK
  • I also get the 1st Sysout , the one with the "+++" delimiter : OK
  • But I don't get the second one, the one with the "****" delimiter : KO

Which I diagnose this way :

  • I get the json response, proving that getCurrentUser() does work.
  • I get the first sysout, that proves that the subscribe code does work
  • I don't get the second sysout which I absolutly cannot understand.

Obviously, I'm interested in the 2nd sysout, because it looks like the code I'd like to get to work, which is : call the myMethod(PulseUser myUser) where myUser comes from the userContextService.getCurrentUser().

A bit clearer :

public void touch(MyData data) {
   //use the mono value of userContextService.getCurrentUser()
   //and call a method on data using the current PulseUser of the Mono
}

Can someone wise help me please ?

Dominique
  • 87
  • 2
  • 10

1 Answers1

0

Finally, solution was found using this post ReactiveSecurityContextHolder is empty in Spring WebFlux

I was trying to access the security context outside of the flux, which caused an empty Mono.

Dominique
  • 87
  • 2
  • 10