Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebClient set Bearer auth token in header

Following scenario:

I have two Microservices A and B. Service A is a Bearer client that has an open api and receives requests from clients that have to be authorized by keycloak. Now I want to send an authorized Request from Service A to Service B, which is also a bearer client.

I thought about adding the functionality as a filter function during the webclient builder process like

@Bean
WebClient webClient() {
    return WebClient.builder()
            .filter(authHeader())
            .build();
}

private ExchangeFilterFunction authHeader(String token) {
    return (request, next) -> next.exchange(ClientRequest.from(request).headers((headers) -> {
        headers.setBearerAuth(token);
    }).build());
}

This is an example I found in another question. It seems to to be the right way to me but can I provide the "String token" parameter at that stage of configuration?

I'm just switching from RestTemplate to WebClient, so sorry I this is a dump question.

EDIT: I am able to set the header manually while building a new WebClient.

return WebClient.builder()
        .defaultHeader("Authorization", "Bearer "+ context.getTokenString())
        .build();

As I know from the RestTemplate, it can be used as a Singleton. There also exists a KeyCloakRestTemplate which injects the header automatically.

WebClient is immutable, so when I inject it, I can't just use it and add the header afterwards. In addition, I can't set this header on startup as I have to wait for a request to take the bearer header and pass it in. So I guess there is not other way than doing it this way?

like image 457
FishingIsLife Avatar asked Dec 11 '20 10:12

FishingIsLife


People also ask

How do I add a Bearer Token to my header?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

How do you set a Bearer Token in WebClient spring boot?

Similar to Basic Auth, we can also setup the Bearer token in WebClient using new method setBearerAuth in HttpHeaders class: void setBearerAuth(String token) //Set the value of the Authorization header to the given Bearer token.

How do I send Authorization header bearer?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.


1 Answers

Or simply set it during the process of sending:

webClient.get()
    .uri(url)
    .headers(h -> h.setBearerAuth(token))
    .retrieve();
like image 57
membersound Avatar answered Oct 13 '22 11:10

membersound