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?
default header
. I have to insert it as header when requesting. Any idea why? – Micromillimeter