Created
April 15, 2021 15:00
-
-
Save aheritier/cc45c1bd7f4e0b861139e304cae13bec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* <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