0

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

Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104

3 Answers3

2

There is one more way to add it by implementing the ExchangeFilterFunction in your WebClient using filter, like below:

WebClient.builder().filter(setJWT());

private ExchangeFilterFunction setJWT() {
        return ExchangeFilterFunction.ofRequestProcessor((clientRequest) -> {
            ClientRequest authorizedRequest = ClientRequest.from(clientRequest).header("AUTHORIZATION","{LOGIC TO GET THE TOKEN}").build();
            return Mono.just(authorizedRequest);
        });
    }

This implementation will take the request before actually calling the API and add the JWT token.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
1

you can use the doOnSuccess

client.post()
      .uri("")
      .body(BodyInserters.fromFormData("username", "XXX")
                    .with("password", "XXXXX"))
      .retrieve()
      .bodyToFlux(JwtToken.class)
      .onErrorMap(e -> new Exception("Error While getting Token", e))
      .doOnSuccess(jwtToken -> {
                client.header(HttpHeaders.AUTHORIZATION, "bearer " + jwtToken)
                      .get()
                      ...
      })
Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
0
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));
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
  • You can use the following client.get().headers(h -> h.setBearerAuth(token.bearer())) You can get references here: https://docs.spring.io/spring-security/site/docs/5.2.12.RELEASE/reference/html/webclient.html#webclient – pazfernando Dec 07 '21 at 17:26