Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* <p>Create a {@link WebClient} using OAuth2 (Auth0) authentication (MTM)</p>
*
* @param clientRegistrationRepository The repository of client registrations
* @param authorizedClientRepository The repository of authorized clients
* @param clientRegistrationId The Client Registration Id to use to get the authentication info (clientId, clientSecret, scope...)
* @param url The base URL of REST Service this client is interacting with
* @param audience The audience to pass to the authentication request sent to Auth0
* @return a {@link WebClient} instance preconfigured to access to the remote service
* @since 1.1.0
*/
@Nonnull
public static WebClient createWebClient(@Nonnull ClientRegistrationRepository clientRegistrationRepository,
@Nonnull OAuth2AuthorizedClientRepository authorizedClientRepository,
@Nonnull String clientRegistrationId,
@Nonnull String url,
@Nonnull String audience) {
Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> customRequestEntityConverter =
new Auth0ClientCredentialsGrantRequestEntityConverter(audience);
DefaultClientCredentialsTokenResponseClient clientCredentialsTokenResponseClient =
new DefaultClientCredentialsTokenResponseClient();
clientCredentialsTokenResponseClient.setRequestEntityConverter(customRequestEntityConverter);
ClientCredentialsOAuth2AuthorizedClientProvider clientCredentialsOAuth2AuthorizedClientProvider =
new ClientCredentialsOAuth2AuthorizedClientProvider();
clientCredentialsOAuth2AuthorizedClientProvider
.setAccessTokenResponseClient(clientCredentialsTokenResponseClient);
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(clientCredentialsOAuth2AuthorizedClientProvider);
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
oauth2Client.setDefaultClientRegistrationId(clientRegistrationId);
return WebClient.builder()
.baseUrl(url)
.apply(oauth2Client.oauth2Configuration())
.build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment