no

How to Secure a Spring Rest Project With Keycloak

1. Overview In this blog, we will cover the basics of securing a Spring project with Keycloak using keycloak-spring-boot-starter and ...

1. Overview

In this blog, we will cover the basics of securing a Spring project with Keycloak using keycloak-spring-boot-starter and keycloak-spring-security-adapter.

2. Limitation

Keycloak is already a well-documented topic that needs no further write up. Here's a link to the documentation: https://www.keycloak.org/documentation.html.

3. The Spring Boot Project

I'm using Spring STS so I created my project with it, but you can use the Spring initializer from the Spring website. 

Here's the content of the pom.xml file. Note that keycloak-spring-security-adapter. is already defined in keycloak-spring-boot-starter.

For a more detailed instruction on how to setup the Keycloak Spring boot starter you may check: https://www.keycloak.org/docs/latest/securing_apps/index.html#_spring_boot_adapter.

<properties>
 <java.version>11</java.version>
 <keycloak.version>4.8.1.Final</keycloak.version>
</properties>

<dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>
 <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-devtools</artifactId>
  <scope>runtime</scope>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
 </dependency>
</dependencies>

<dependencyManagement>
 <dependencies>
  <dependency>
   <groupId>org.keycloak.bom</groupId>
   <artifactId>keycloak-adapter-bom</artifactId>
   <version>${keycloak.version}</version>
   <type>pom</type>
   <scope>import</scope>
  </dependency>
 </dependencies>
</dependencyManagement>

3.1 Configuration

There are actually 2 ways we can secure a Spring project with Keycloak.

3.1.1 Using Keycloak Spring Boot Starter

This is the standard approach where we define the keycloak client configurations from keycloak.json to application.yml or to the standard Spring configuration file.
keycloak:
  enabled: true
  realm: dev
  auth-server-url: http://localhost:8083/auth
  ssl-required: external
  resource: dev-api
  bearer-only: true
  confidential-port: 0
  use-resource-role-mappings: false
  principal-attribute: preferred_username
  cors: true
  security-constraints:
    - auth-roles:
      - User
      security-collections:
      - name: unsecured
        patterns:
        - /users
    - auth-roles: 
      - Admin
      security-collections:
      - name: secured
        patterns:
        - /admin
logging:
  level:
    org.apache.catalina: DEBUG

In this example configuration, we define 2 URL patterns /users and /admin which are both secured by their respective roles. Take note that security-constraint is composed of auth-roles and security-collections array.

Enabling the log on org.apache.catalina will let us see the security check on the given URL when we invoke the API.

At the same time, if we set the config resolver to KeycloakSpringBootConfigResolver, then we can also configure the HttpSecurity.

Below is part of the class that extends KeycloakWebSecurityConfigurerAdapter. Keycloak provides this base class for easier configuration as well as the @KeycloakConfiguration annotation.

@Bean
public KeycloakConfigResolver keycloakConfigResolver() {
 return new KeycloakSpringBootConfigResolver();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
 super.configure(http);
 http.cors() //
   .and() //
   .csrf().disable() //
   .anonymous().disable() //
   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //
   .and() //
   .authorizeRequests() //
   .antMatchers("/users*").hasRole("USER") //
   .antMatchers("/admin*").hasRole("ADMIN") //
   .anyRequest().denyAll(); //
}

3.1.2 Using Keycloak Spring Security Adapter

For Spring developers I think this is the mode where they are more familiar. Basically, it will use the configuration from keycloak.json (ignoring the settings in application.yml).

For this to work we need to add a dependency to our project:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Delete the Keycloak related configurations in application.yml including the security constraints. And remove the keycloakConfigResolver bean, as this tells Spring to ignore the keycloak.json file. This will leave us with the security in method configure(HttpSecurity http), which is still good.

By default, the project will look for a keycloak.json file inside the WEB-INF folder, but since the project is of jar type, this folder is not available, so we need to set a system variable in Spring STS:

keycloak.configurationFile=classpath:keycloak.json



And make sure that we have the keycloak.json file inside our src/main/resources folder.

The complete source code is available at Github: https://github.com/czetsuya/Spring-Keycloak-with-REST-API

Related

spring-rest 1526498007041640603

Post a Comment Default Comments

1 comment

Mack said...

Hi Sir,

I have mailed you regarding keycloak,kindly assist me.

Thanks

item