Monday, November 18, 2024
Google search engine
HomeLanguagesJavaHow to Integrate Keycloak with Spring Boot and Spring Security?

How to Integrate Keycloak with Spring Boot and Spring Security?

Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorization, and more. Some of the features of Keycloak mention below.

Features of Keycloak

Before following this article you must refer to these two articles:

Spring Boot Adapter

Adding the Dependency

To add the starter to your project using Maven, add the following to your dependencies:

XML




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


Add the Adapter BOM dependency:

XML




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


Changes in the application.properties file

You can configure the realm for the Spring Boot adapter via the normal Spring Boot configuration. For example:

keycloak.realm = your_realm
keycloak.auth-server-url = http://127.0.0.1:8080
keycloak.ssl-required = external
keycloak.resource = your_client_id
keycloak.credentials.secret = your_client_secret
keycloak.use-resource-role-mappings = true

Note: Make sure to replace the placeholders (your_realm, your_client_id, your_client_secret) with your Keycloak realm, client ID, and client secret.

Spring Security Adapter

Adding the Dependency

To add the starter to your project using Maven, add the following to your dependencies:

XML




<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-security-adapter</artifactId>
    <version>21.1.2</version>
</dependency>


Java Configuration

Keycloak provides a KeycloakWebSecurityConfigurerAdapter as a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods. While its use is not required, it greatly simplifies your security context configuration.

Java




@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
    /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }
 
    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(buildSessionRegistry());
    }
 
    @Bean
    protected SessionRegistry buildSessionRegistry() {
        return new SessionRegistryImpl();
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .authorizeRequests()
                .antMatchers("/customers*").hasRole("USER")
                .antMatchers("/admin*").hasRole("ADMIN")
                .anyRequest().permitAll();
    }
}


RELATED ARTICLES

Most Popular

Recent Comments