Search code examples
spring-bootspring-webfluxspring-webclient

adding JWT token in request in reactive way in webflux


I am using WebClient to call Rest API Which are secured by JWT token. //To get Token

JwtToken token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToFlux(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))
                .blockLast(); 

//Call secure API

 WebClient client = consorsWebClientBuilder
                .defaultHeaders(token.bearer())
                .build();

              client
                .get()
                .uri(someURI)
                .retrieve()
                .bodyToMono(String.class)

i am calling Block in reactive chain, so web flux is not happy and saying

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-client-epoll-12

How can i add token in reactive way ? Note, I Can create Filter but still in filter also i need to call Block


Solution

  • I used map for this, not the best solution but does the work
    
    Mono<JwtToken>  token = client.post()
                    .uri("")
                    .body(BodyInserters.fromFormData("username", "XXX")
                            .with("password", "XXXXX"))
                    .retrieve()
                    .bodyToMon(JwtToken.class)
                    .onErrorMap(e -> new Exception("Error While getting Token", e))
    
    
    return token
         .flatMap(token -> callApi(request, token));