Search code examples
springspring-bootspring-securityspring-webfluxspring-webclient

Spring WebClient header from ReactiveSecurityContext


I'm trying to set WebClient header value accordingly to the authenticated user, something like this:

webClient.post().header(HttpHeaders.AUTHORIZATION, getUserIdFromSession())...

and

public String getUserIdFromSession() {
  Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);

  //do something here to get user credentials and return them
}

Should I store the required header value somewhere else? Because in reactive way, everything returns a Mono/Flux and I'm currently unable to use the authenticated user data as I have used it with Spring MVC. There I could just do SecurityContextHolder.getContext().getAuthentication()


Solution

  • Is there a reason you aren't just flatmapping the Authentication and then calling the webclient? You could also just return the Mono<String> from your method

    ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
    .flatMap(auth -> webClient.post().header(HttpHeaders.AUTHORIZATION, auth.getUserId()).exchange();