How to register Keycloak to Spring Eureka Server

Viewed 1262

There are 3 service:

  • user-service
  • eureka-discovery-service
  • keycloak-authoriztaion-service

I have configured eureka server it's up and running and I have registered the user-service with: @EnableDiscoveryClient

application.properties(user-service)

spring.application.name=user-service
server.port=8040
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka

I can see the registered user-services it's okay for Spring Boot applications.

How can I register Keycloak into the Eureka Discovery Service?

1 Answers

You can try using spring security and the built In support for keycloak. (This guide)[https://www.baeldung.com/spring-boot-keycloak] gives a pretty complete example.

For completeness sake, here are the relevant excerpts from the guide. If you have not already, you will need to add springs keycloak dependencies to your pom.xml

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.keycloak.bom</groupId>
            <artifactId>keycloak-adapter-bom</artifactId>
            <version>3.3.0.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

...
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>

You can configure spring through the application properties. Then simply set up your Spring security configuration class extending the keycloak adapter.

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(
      AuthenticationManagerBuilder auth) throws Exception {

        KeycloakAuthenticationProvider keycloakAuthenticationProvider
         = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
          new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(
          new SessionRegistryImpl());
    }
 }
Related