Niraj Sonawane
Niraj Sonawane

Reputation: 11055

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

Upvotes: 0

Views: 6495

Answers (4)

Cugomastik
Cugomastik

Reputation: 1009

maybe this helps:

public class WebClientExample {
        public static void main(String[] args) {
            try {
                String bearerToken = "your_token_here"; // Replace with your actual token
                String uri = "your_api_endpoint_here"; // Replace with your actual URI
    
                WebClient webClient = WebClient.builder()
                        .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken)
                        .build();
    
                String response = webClient.post()
                        .uri(uri)
                        .retrieve()
                        .bodyToMono(String.class)
                        .block();
    
                System.out.println("Response: " + response);
            } catch (Exception e) {
                System.err.println("Error while sending request: " + e.getMessage());
            }
        }
    }

Upvotes: 0

user16957024
user16957024

Reputation: 21

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.

Upvotes: 2

Niraj Sonawane
Niraj Sonawane

Reputation: 11055

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));

Upvotes: 0

Toerktumlare
Toerktumlare

Reputation: 14712

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()
                      ...
      })

Upvotes: 1

Related Questions