no

Secure Spring Boot 2 REST API with Keycloak 8

I. Introduction Keycloak is an identity and access management solution that can be rolled out of the box with little configuration. Fu...

I. Introduction

Keycloak is an identity and access management solution that can be rolled out of the box with little configuration. Furthermore, it's open-source which makes it popular among developers.

I have written several articles on how to secure a frontend and backend application using Keycloak available at https://czetsuya-tech.blogspot.com/2019/10/keycloak-authentication-and.html. The purpose of this tutorial is to cover the latest version of Keycloak, which as of the time of this writing is 8.0.1.

This tutorial will secure a Spring REST API by using the Keycloak Spring Boot adapter and Spring Boot starter security.

II. Create a Realm in Keycloak

Startup Keycloak with the keycloak.profile.feature.upload-scripts=enabled parameter. If you will decide to import the realm that I will commit along with this project.

>standalone.bat -Djboss.socket.binding.port-offset=1 -Dkeycloak.profile.feature.upload_scripts=enabled

realm name=balambgarden
client (confidential)=sso-client
client (bearer)=api-services

Create the following roles and users:

Role=PROMOTER, User=sarah / kerrigan
Role=SUPERVISOR, User=jim / raynor

Or you can opt to import the realm and users in the project's config folder.

III. The Spring Project

1.) Dependencies

The following dependencies must be included in your project.
  • keycloak-spring-boot-2-adapter
  • keycloak-tomcat7-adapter-dist
  • keycloak-spring-security-adapter
  • spring-boot-starter-security

2.) Define a Custom KeycloakSpringBootConfigResolver Configuration in its Own Class

See the code below.

3.) Extend the KeycloakWebSecurityConfigurerAdapter class

More documentation about this class is available at https://www.keycloak.org/docs/latest/securing_apps/.

See the code below.

4.) Create a REST Controller Class

See the code below.

5.) Update the application.properties File 

See the code below.

IV. Testing

To test the application run Postman and import the collection inside the project's config folder.

There are 2 sub-folders inside the collection. Sarah has a promoter role and Jim which has a supervisor promoter. Both Sarah and Jim will not be able to access the isAuthenticated tests and Sarah will not be able to access the URL that is only accessible by a supervisor role.

Related

coding 4076245750581032489

Post a Comment Default Comments

item