Is it possible to use Oauth2 authentication with the new RestClient?

940 Views Asked by At

With WebClient I use this code to make web client work with a Spring Resource Server endpoint.

Is it possible to make this code work with the new RestClient?

@Bean
UserClient userClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = 
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
oauth2.setDefaultOAuth2AuthorizedClient(true);
        
WebClient webClient = WebClient.builder()
    .baseUrl("http://127.0.0.1:8091")
    .apply(oauth2.oauth2Configuration())
    .build();       
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
UserClient userClient = factory.createClient(UserClient.class);
return userClient;
}

@Bean
OAuth2AuthorizedClientManager authorizedClientManager(
      ClientRegistrationRepository clientRegistrationRepository,
      OAuth2AuthorizedClientRepository authorizedClientRepository) {

OAuth2AuthorizedClientProvider authorizedClientProvider =
      OAuth2AuthorizedClientProviderBuilder.builder()
        .clientCredentials()
        .authorizationCode()
        .refreshToken()
        .build();

DefaultOAuth2AuthorizedClientManager authorizedClientManager =
     new DefaultOAuth2AuthorizedClientManager(
       clientRegistrationRepository, authorizedClientRepository);

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

return authorizedClientManager;
}

Is there a solution possible like the code below?

RestClient restClient = RestClient.builder()
    .baseUrl("http://127.0.0.1:8091")
    .apply( ??????? )
    .build();
1

There are 1 best solutions below

0
Steve Riesenberg On

There is not built-in support for RestClient in Spring Security yet. Please see #13588 to follow progress on this issue.