Keycloak is an open-source Identity and Access Management solution, providing features such as Single Sign-On (SSO), OAuth 2.0, and OpenID Connect. In this tutorial, we will integrate Keycloak with a Spring Boot application for secure authentication and authorization.
Prerequisites
- Java JDK installed on your machine
- Maven or Gradle installed
- Keycloak installed (You can download Keycloak and follow their installation guide)
- Basic understanding of Spring Boot
Step 1: Setup a Spring Boot Project
First, let’s create a new Spring Boot project. You can do this manually or use the Spring Initializr to generate a project with the required dependencies.
For Maven, add the following dependencies:
- Spring Web
- Spring Security
- Spring Boot DevTools
- Keycloak Spring Boot Starter
Here’s an example pom.xml
for Maven:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot DevTools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Keycloak Spring Boot Starter -->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>15.0.2</version>
</dependency>
</dependencies>
Step 2: Configure Keycloak
- Start your Keycloak server and create a new realm, client, and user. You can refer to the Keycloak documentation for detailed steps.
- Once your realm, client, and user are set up, note down the following information:
- Realm Name
- Client ID
- Client Secret
- Keycloak Base URL (e.g.,
http://localhost:8080/auth
)
Step 3: Configure Spring Boot
Create a application.properties
or application.yml
file in your Spring Boot src/main/resources
directory and add the Keycloak configuration:
application.properties
:
# Keycloak Configuration
keycloak.realm=myrealm
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.ssl-required=external
keycloak.resource=myclient
keycloak.credentials.secret=yourclientsecret
keycloak.use-resource-role-mappings=true
# Server Port
server.port=8081
application.yml
:
# Keycloak Configuration
keycloak:
realm: myrealm
auth-server-url: http://localhost:8080/auth
ssl-required: external
resource: myclient
credentials:
secret: yourclientsecret
use-resource-role-mappings: true
# Server Port
server:
port: 8081
Step 4: Create a Controller
Let’s create a simple REST controller to test our authentication:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, secured user!";
}
}
Step 5: Enable Security
Create a security configuration class to enable Keycloak security:
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/hello").hasRole("user")
.anyRequest().permitAll();
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Bean
public SimpleAuthorityMapper grantedAuthorityMapper() {
SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
grantedAuthorityMapper.setPrefix("ROLE_");
grantedAuthorityMapper.setConvertToUpperCase(true);
return grantedAuthorityMapper;
}
}
Step 6: Run the Application
Now you can run your Spring Boot application. It will start on port 8081 (as configured). When you access the /hello
endpoint, it will redirect you to Keycloak for login. After successful authentication, you will see the “Hello, secured user!” message.
Conclusion
In this tutorial, we’ve integrated Keycloak with a Spring Boot application for secure authentication. Users will be redirected to Keycloak’s login page for authentication, and upon successful login, they will have access to the secured endpoints. This setup allows for Single Sign-On (SSO) and centralized authentication management using Keycloak. Further customization can be done based on your application’s requirements and Keycloak’s features.