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(); } } |
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
- Open Source product that allows Single Sign On (SSO) with Identity and Access Management.
- Authentication and Authorization
- Centralized management of users
- It is developed using Java
- It provides an adapter to integrate with Spring Boot and Spring Security
- User Federation
- Multi-Factor Authentication (MFA)
- Social Login
Before following this article you must refer to these two articles: