Header Ad

Thursday, September 19, 2024

Implementing SSO with Keycloak in a Spring Boot Application

Introduction

Single Sign-On (SSO) is a powerful authentication mechanism that allows users to log in once and gain access to multiple applications. In this blog post, we’ll walk you through the steps to implement SSO using Keycloak in a Spring Boot application.

Step 1: Add Maven Dependencies

First, add the necessary dependencies to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Step 2: Configure Keycloak

Create a keycloak.json file in your src/main/resources directory with the following content:

{
  "realm": "your-realm",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "your-client-id",
  "credentials": {
    "secret": "your-client-secret"
  },
  "confidential-port": 0
}

Step 3: Spring Security Configuration

Create a security configuration class to integrate Keycloak with Spring Security:

import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

@KeycloakConfiguration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated();
    }
}

Step 4: Application Properties

Add the following properties to your application.properties file:

keycloak.realm=your-realm
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.resource=your-client-id
keycloak.credentials.secret=your-client-secret
keycloak.ssl-required=external
keycloak.use-resource-role-mappings=true

Step 5: Create a Controller

Create a simple controller to test the SSO setup:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/public")
    public String publicEndpoint() {
        return "This is a public endpoint.";
    }

    @GetMapping("/private")
    public String privateEndpoint() {
        return "This is a private endpoint.";
    }
}

Conclusion

Run your Spring Boot application and navigate to the /private endpoint. You should be redirected to the Keycloak login page. After logging in, you will be able to access the private endpoint. This setup provides a basic SSO implementation using Keycloak with Spring Boot. Customize it further based on your specific requirements.

Happy coding! 🚀



No comments:

Post a Comment