Java

Setting up spring-boot application as OAuth 2.0 Resource Server

By June 6, 2023 No Comments

Step 1: Set up Keycloak

  1. Install and set up Keycloak by following the official documentation: https://www.keycloak.org/documentation.html
  2. 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.
  3. 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.
  4. 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

  1. 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.
  2. 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); } }
  1. Update the SecurityConfig class to secure your API endpoints based on your requirements.
  2. 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

  1. Add the Keycloak Spring Security Adapter dependency to your project’s pom.xml file

dependency>
    org.keycloak
    keycloak-spring-security-adapter
/dependency>
  1. 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(); } }
  1. 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(); } }
  1. Replace “your-realm,” “your-client-id,” and “your-client-secret” with the corresponding values from your Keycloak setup.

Step 4: Test the Configuration

  1. Run your Spring Boot application.
  2. Access your protected API endpoints and ensure that Keycloak authentication is working as expected.
  3. 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.

Leave a Reply