添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Recently, we migrated from RestTemplate to WebClient in one of our Spring Boot projects. Our goal was to simplify OAuth2 token management for internal service-to-service communication. Our use case? To make secure REST calls between services by authenticating with Keycloak or EKS token server using the client_credentials OAuth2 grant type.
  • Our services needed to authenticate with Keycloak or EKS token server for secure internal communication
  • We were provided with essential credentials: client_id, client_secret, and token_uri
  • We wanted automatic token retrieval and header injection in each REST call — avoiding manual token management or repetitive boilerplate code
  • Reactive and non-blocking by default
  • Seamless integration with Spring Security's OAuth2 client
  • Cleaner, more readable code
  • Automatic token handling using OAuth2AuthorizedClientManager
  • @Bean
    public ReactiveClientRegistrationRepository clientRegistrationRepository() {
        ClientRegistration registration = ClientRegistration.withRegistrationId("keycloak")
                .tokenUri("https://dummy-oauth-server.com/oauth/token")
                .clientId("demo-client-id")
                .clientSecret("demo-client-secret")
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .build();
        return new InMemoryReactiveClientRegistrationRepository(registration);
        
    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(...) {
        OAuth2AuthorizedClientProvider provider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build();
        DefaultOAuth2AuthorizedClientManager manager =
            new DefaultOAuth2AuthorizedClientManager(clients, authorizedClients);
        manager.setAuthorizedClientProvider(provider);
        return manager;
        
    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager manager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 =
            new ServletOAuth2AuthorizedClientExchangeFilterFunction(manager);
        oauth2.setDefaultClientRegistrationId("keycloak");
        return WebClient.builder()
            .apply(oauth2.oauth2Configuration())
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .build();
        
  • WebClient + OAuth2 makes token management automatic
  • It's the modern way to handle internal service authentication
  • We reduced code complexity and improved security alignment
  •