Step 1: Set up Keycloak
- Install and set up Keycloak by following the official documentation: https://www.keycloak.org/documentation.html
- Create a new realm in Keycloak to manage your application’s security. You can do this by logging into the Keycloak admin console and navigating to the “Realms” section.
- Inside your realm, create a new client representing your Spring Boot application. Configure the client as a “Confidential” type and enable the “Service Accounts Enabled” option.
- Note down the “Client ID” and “Client Secret” values of the client you created. You will need these later.
Step 2: Set up a Spring Boot Application
- Create a new Spring Boot project using your preferred development environment or the Spring Initializr (https://start.spring.io/). Include the necessary dependencies for Spring Security and OAuth 2.0.
- Configure your Spring Boot application to use the Spring Security OAuth 2.0 framework. You can do this by adding the following configuration classes
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.oauth2ResourceServer().jwt();
}
}
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
private final AuthenticationManager authenticationManager;
public OAuth2Config(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("your-client-id")
.secret("your-client-secret")
.authorizedGrantTypes("client_credentials")
.scopes("read", "write")
.accessTokenValiditySeconds(3600);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
- Update the SecurityConfig class to secure your API endpoints based on your requirements.
- Replace the placeholder values “your-client-id” and “your-client-secret” in the OAuth2Config class with the actual values of the client you created in Keycloak.
Step 3: Configure Keycloak integration
- Add the Keycloak Spring Security Adapter dependency to your project’s pom.xml file
dependency>
org.keycloak
keycloak-spring-security-adapter
/dependency>
- Create a new configuration class to integrate Keycloak with your Spring Boot application:
@Configuration
@EnableWebSecurity
@KeycloakConfiguration
public class KeycloakSecurityConfig 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());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/api/**").hasRole("user")
.anyRequest().permitAll();
}
}
- In your application.properties file, add the following Keycloak configuration properties:
@Configuration
@EnableWebSecurity
@KeycloakConfiguration
public class KeycloakSecurityConfig 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());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/api/**").hasRole("user")
.anyRequest().permitAll();
}
}
- Replace “your-realm,” “your-client-id,” and “your-client-secret” with the corresponding values from your Keycloak setup.
Step 4: Test the Configuration
- Run your Spring Boot application.
- Access your protected API endpoints and ensure that Keycloak authentication is working as expected.
- You can obtain an access token from Keycloak and include it in the Authorization header of your API requests to authenticate with the resource server.
That’s it! You have successfully set up a Spring Boot application as an OAuth 2.0 Resource server using Keycloak.