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 keycloa...

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

COMMENTS

mas template
Name

amazon,1,angular,8,bigdata,2,business,1,course-spring,27,courses,6,database,4,docker,3,java,50,kafka,1,keycloak,4,microservices,5,mysql,1,neworking,1,nosql,2,php,1,pinned,2,react,3,server management,7,shared drive,1,spring,7,synology,1,troubleshooting,2,web,1,wordpress,1,
ltr
item
toztech: Secure Spring Boot REST Project with Keycloak
Secure Spring Boot REST Project with Keycloak
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZQ0t0vdb7AtpO3sCzl0SmK07cGvRAH9AUxsw3F3H-PiRvlgYYrEUCXCA33qF-sg2KupSNzmUShAY0UjuR3ZvfuoEi7zyUXjwNZCJflpOBlNbN0OT4AuliNi6n70KOuXUD4bfqMkd6Djg/s320/spring-keycloak.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZQ0t0vdb7AtpO3sCzl0SmK07cGvRAH9AUxsw3F3H-PiRvlgYYrEUCXCA33qF-sg2KupSNzmUShAY0UjuR3ZvfuoEi7zyUXjwNZCJflpOBlNbN0OT4AuliNi6n70KOuXUD4bfqMkd6Djg/s72-c/spring-keycloak.png
toztech
https://toztech.blogspot.com/2018/12/secure-spring-boot-rest-project-with.html
https://toztech.blogspot.com/
https://toztech.blogspot.com/
https://toztech.blogspot.com/2018/12/secure-spring-boot-rest-project-with.html
true
2554149350007112447
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content