Search code examples
javaspring-bootload-balancingspring-cloudkeycloak

Integrate Spring Cloud load balancing with KeycloakRestTemplate


I have a microservice landscape configured with Spring Cloud discovery so I'm able to access other service instances just using their id's:

public class MyClass {

    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    public String doOtherStuff() {
        String results = restTemplate.getForObject("http://stores/stores", String.class);
        return results;
    }
}

Now I want to access a service which needs OAuth2 authorization. I use a Keycloak server in order to provide it and Keycloak already provides an adapter with an specific KeycloakRestTemplate. Anyway, how to enhance it with load balancing?


Solution

  • We need to create a specific KeycloakRestTemplate which will use a LoadBalancerInterceptor:

    @Configuration
    @EnableWebSecurity
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
    public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    
        @Bean
        @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        @LoadBalanced
        public KeycloakRestTemplate keycloakRestTemplate(
                KeycloakClientRequestFactory keycloakClientRequestFactory,
                LoadBalancerInterceptor interceptor) {
            KeycloakRestTemplate result = new KeycloakRestTemplate(
                keycloakClientRequestFactory);
            // Add the interceptor for load balancing
            result.getInterceptors().add(interceptor);
            return result;
        }
    
        //More configurations for keycloak
    
    }
    

    So there's the chance of getting an Authorized / LoadBalanced template:

    @Autowired
    @LoadBalanced
    protected KeycloakRestTemplate restTemplate;
    

    See also: