I am using WebClient in Spring MVC servlet based application (non-reactive) for accessing resources over HTTP from other microservices. Few of the resources are protected by client_credentials OAuth2 flow. It is very convenient to configure RestTemplate with OAuth2 Client Credentials, but now I am stuck configuring the same with WebClient. I can always get the Bearer token manually and then set it in WebCLient setBearerAuth()
method, but that requires a lot of manual plumbing. My question is - does WebClient support Exchange Filter for automatic Client Credentials flow when used in Spring MVC application?
UPDATE:
I have found ServletOAuth2AuthorizedClientExchangeFilterFunction
that should solve client credentials auth flow. I am using the below code:
@Bean
WebClient webClient(ClientRegistrationRepository clientRegistrations, OAuth2AuthorizedClientRepository authorizedClients) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
oauth2.setDefaultClientRegistrationId("cart67");
oauth2.setDefaultOAuth2AuthorizedClient(true);
final WebClient webClient = WebClient.builder()
.apply(oauth2.oauth2Configuration())
.build();
return webClient;
}
But the issue now is that this WebClient can not make calls to remote resource server when called from a scheduled job. I get the below error:
reactor.core.Exceptions$ErrorCallbackNotImplemented:
java.lang.IllegalArgumentException: request cannot be null
Caused by: java.lang.IllegalArgumentException: request cannot be null
at org.springframework.util.Assert.notNull(Assert.java:198)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Things work fine if i use this WebClient from a MVC controller instead of scheduled job. Any help on this would be appreciated.