Secure Spring Boot REST Project with Keycloak
Tech-Today

Secure Spring Boot 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 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




- Create A Restful Web Service In Spring
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactTo prepare the project from future development, we will be creating a multi-maven project layout. Unfortunately,...

- Keycloak Overlay Installation Failed
While playing with keycloak I have encountered several related problems: Keycloak 3.2.1 downloadable with samples is not working running.Installing keycloak 3.2.1 overlay on Wildfly 10.1.Final fails.Errors are:Caused by: org.jboss.modules.ModuleNotFoundException:...

- How To Signin To Keycloak Using Google
There are 3 set of steps that we must follow in order to come up with a web project that will allow us to login using google's identity provider. Set 1 - Create a google applicationCreate a google application at https://console.developers.google.com...

- How To Setup Seam3-security In Jboss 7
Recently, I've done some research on several Java Security Framework that can perform authentication, authorization and cryptography. I've worked with Apache Shiro, it's really good and complete but I've found several problems like there's...

- How To Use Primefaces With Jboss 7.1.3
This tutorial will teach us how to use primefaces with jboss 7.1.3. Requirements:  1.) primefaces 3.5  2.) jboss 7.1.3  3.) maven javaee6 generated project (ear, war, ejb) Steps: 1.) Add primefaces module in jboss.   a.) In JBOSS_HOME/modules...



Tech-Today








.