Berlin, Germany

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

Overview

In this article, we’ll be covering the following topics :

  • Installing and setting up a keycloak server in your machine
  • Keycloak integration with a Spring Boot application
  • Using Spring Security

What is Keycloak?

Keycloak is an open source identity and access management solution which mainly aims at applications and services.

Users can authenticate with Keycloak rather than individual applications.

So, the applications don’t have to deal with login forms, authenticating users and storing users. Once logged-in to Keycloak, users don’t have to login again to access different applications.

Same thing is applicable to sign-out. Keycloak offers everything a sophisticated user management tool needs – without having to log on repeatedly with every login and into every system-as well as system security, social logins, support for mobile apps and integration into other solutions.

In simple terms, Keycloak serves as a solution to manage authentication and authorization features. For more details, you can check out the official documentation available in the official website.

Installing and setting up Keycloak

Keycloak can be used as a standalone application or with Docker/Kubernetes. For this article we will use the Standalone server distribution.

  1. Download the Standalone server distribution here. The latest version as of now is 11.0.0.

If you’re using linux, make sure to download the tar.gz version.

  1. Once downloaded, extract the folder and start Keycloak from the terminal.

cd keycloak-11.0.0/ cd bin/ ./standalone.sh -Djboss.socket.binding.port-offset=100

  1. Now with Keycloak up and running, open up a browser and visit http://localhost:8180 to create an admin login.

  1. After setting up an username (e.g. codefiction) and a password, click Create and you should expect a “User created” message to assert everything worked.
  2. Go to the Administrative Console and enter the admin credentials you just registered.

Getting started with Keycloak

After logging in, a default Master realm should show up.

Navigate to the upper left corner to discover the “Add realm” button and add a new realm called Spring-Boot-Keycloak.

After creating a new realm, we should be redirected to our Spring-Boot-Keycloak realm configuration where all the following operations will be executed.

Creating a new client

Keycloak comes with built-in clients that you can check by navigating to the Clients page.

To create a client for our application, we can click the “Create” button on the upper right corner of the clients table.

Set a client id for identification and click “Save”.

In the next screen, we can leave all the default configuration intact except for the “Valid Redirect URIs field” where we need to specify the application URL that will be used in this client for authentication.

Setting up a Role and a User

Since Keycloak uses Role-Based access, all users must have a defined role.

Navigate to the “Roles” page and add a role by clicking the “Add Role” button in the upper right corner of the roles table.

To create a user role, specify a name and a description.

Now that we have a user role, we may go to the “Users” page and add some data to it.

Click the “Add user” button, specify the username, first name and last name of an user and click “Save” to display a page with the details envolved.

To set a password to the defined used, go to the “Credentials” tab next to “Attributes” and “Role Mappings”.

Now to assign the user role to our user_one, navigate to the “Role Mappings” tab, select the user role in the “Available Roles” section and move it to the “Assigned Roles”.

How to generate an Access Token with Keycloak’s API

To create our login page, we’ll use Keycloak’s REST API to generate and refresh access tokens through the following steps :

  1. Acquire an access token by sending a POST request to :

http://localhost:8180/auth/realms/master/protocol/openid-connect/token

  1. Specify as the POST request body :

{ ‘client_id’: ‘your_client_id’, ‘username’: ‘your_username’, ‘password’: ‘your_password’, ‘grant_type’: ‘password’ }

  1. Place the access token in the Authorization header :

headers: { ‘Authorization’: ‘Bearer’ + access_token }

  1. Send a POST request to the same URL as before to refresh the access token when it expires, make sure to include in its body the refresh token instead of the username and password :

{ ‘client_id’: ‘your_client_id’, ‘refresh_token’: refresh_token_from_previous_request, ‘grant_type’: ‘refresh_token’ }

Integration with a Spring Boot application

Since the Keycloak Spring Boot adapter is fully integrated with Spring Boot’s auto-configuration, all we need to do is add the Keybloak Spring Boot starter to our project.

Make sure to include in your maven pom.xml file :

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

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

With this configuration, we’ll enable the following embedded containers when using Spring Boot Keycloak Starter :

  • Tomcat
  • Undertow
  • Jetty

Creating our Web Page

For our web page, we’ll use Thymeleaf, a modern server-side Java template engine for both web and standalone environments.

We’ll have three pages to handle all requests :

  • users.html : page with access restricted to only authenticated users with the user role
  • layout.html : simple layout page with two fragments used for both the external and users page
  • external.html : a facing web page for public access

Creating our Spring Boot application

Our application will consist of five main files (four classes and one interface) :

  • CodefictionDemoProjectApplication : Main class, used only to bootstrap and run the application with Spring Boot
  • Config : Configuration class with all the specifications and details regarding Keycloak
  • User : Simple class to create the user entity and set its getters and setters
  • UserDAO : Interface that extends CrudRepository to handle DB operations on top of the user entity
  • WebController : Used to map the internal and external URLs to the appropriate Thymeleaf templates

We’re also using as dependencies :

  • Lombok
  • Spring Security
  • Spring Web
  • Spring Data JPA
  • Thymeleaf and Keycloak (as we previously mentioned)

For the source code, you can click here.

Keycloak Configuration

In the application.properties file, we enter the basic configuration for our Keycloak integration :

// Set here the path specified in keycloak.auth-server-url
keycloak.auth-server-url=http://localhost:8180/auth
// Set here your realm name
keycloak.realm=Spring-Boot-Keycloak
// Set here the client named in the admin console
keycloak.resource=login-application
keycloak.public-client=true

As security constraints (not needed because we’re using Keycloak Spring Security Adapter) :

keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/customers/*

These ensure that all requests sent to /users/* will only be authorized if it’s requested by someone with the user role.

As additional configuration, we set the following to populate our controller’s Principal with a proper user :

keycloak.principal-attribute=preferred_username

Running the application

To test our application, start it through the IDE and visit http://localhost:8081.

Once we log in as the user we defined previously, Keycloak verifies our authorization and redirects us to the users files page with our example data.

Endnotes

In the next posts we will cover using oauth2, registering and logging in using Google, Github, etc.

All source code from this article is available here in our GitHub page, feel free leave a comment or suggestion below for what you’d like for us to cover in the next article.

Related Posts
12,235 Comments

[…] best online blackjack site for real money […]

[…] sildenafil 100mg price at walmart […]

[…] cialis online no prescription […]

[…] 10 mg cialis daily […]

[…] viagra 50mg buy […]

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://4utimes.com/kerala-covid-updates-8516-cases/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://jasat.nl/2018/11/14/why-i-say-old-chap-that-is-spiffing-bodge-blag-pardon/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://masumisakagami.com/?p=197

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://fdj4.com/guestbook.asp?Page=9

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://www.tanvietsecurity.com/vi-sao-nguoi-hoi-phuc-co-the-tai-nhiem-covid-19/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://www.hxztg.com/?proshow-tid-8-pid-368-ptype-127.html

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://diasporra.com/nefyn-beach-landslide-people-warned-to-keep-away/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://www.ellideleon.info/2020/02/11/hello-world/

[…] purchase cialis […]

[…] cheap viagra jelly […]

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://cheapairjordanpro.com/situs-slot-deposit-pulsa-yang-mengutungkan/

[…] sildenafil 100 mg tablet reviews […]

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://manyvideogames.com/questions/videogames-or-video-games/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://einearchebauen.com/aloha-welt

ivermectin for sale

ivermectin tablets uk

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://russoslaw.com/hello-world-2

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://www.divinooweb.com/component/k2/author/8594.feed

price for combivent

albuterol inhaler for sale

ivermectin pills human

stromectol pill for humans

tadalafil citrate

tadalafil capsules

buy levitra online

goodrx viagra

ivermectin 3mg pill

ivermectin pills for sale

ivermectin for dogs

ivermectin coronavirus

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://guskish.com/2020/01/21/the-chinese-festival/

albuterol mdi inhaler

albuterol 95mcg

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://www.perseyda.com/historias_de_amor/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://stopsmoking-tips.org/health-effects-of-smoking/health-effects-of-smoking-on-nonsmokers

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://erpcx.net/hello-world/

flccc protocol

flccc ivermectin

flccc ivermectin

where to get ivermectin

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://servicecanaria.com/logo10/

flccc ivermectin

flccc ivermectin

ivermectin us fda

over the counter ivermectin

ivermectin 15 mg

ivermectin buy uk

cheap stromectol

stromectol covid

cost of ivermectin lotion

stromectol where to buy

ivermectin lotion for scabies

ivermectin 2%

ivermectin 0.5 lotion

stromectol tablets for humans for sale

ivermectin india

ivermectin in india

ivermectin price usa

stromectol usa

ivermectin virus

ivermectin 1mg

ivermectin stromectol

ivermectin goodrx

how much does ivermectin cost

ivermectin treatment for covid

ivermectin buy

ivermectin buy online

where to get ivermectin

ivermectin tablets for humans

ivermectin in canada

stromectol tablets

stromectol tablets

where to get ivermectin

ivermectin cost

where can i get ivermectin

ignition casino check by courier

ignition casino legal in california

ivermectin buy

ivermectin ontario

cialis without a doctor prescription

cialis best price

prednisone 40mg drug

buy prednisone 5mg online cheap

cialis amazon

cialis dosis

how to get tadalafil over the counter

where can you get tadalafil

provigil costo in farmacia

provigil online pharmacy

tadalafil liquid

what is cialis

ivermectin cost

stromectol generic

where to buy ivermectin

ivermectin for sale

order viagra by mail

cheap viagra mastercard

marley drugs tadalafil

buy viagra online

generic viagra images

how to take viagra for maximum effect

stromectol tablets for humans for sale

stromectol tablets for humans

where to buy cialis

online generic cialis canada

cialis buy in canada

cialis buy in canada

cialis black

generic cialis medication

buy sildenafil pills from canada

cheap sildenafil 100mg

daily cialis

order generic cialis online uk

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://zibelinecreation.com/une-rentree-couture-tout-azimut/

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://www.kilmaluagbay.co.uk/2016/09/27/isle-of-skye-scotland/

cheapest generic cialis online pharmacy

tadalafil generic

stromectol sale

stromectol ivermectin buy

buy sildenafil pills from canada

sildenafil pills

cheap sildenafil online in usa

sildenafil pills for men

cialis tadalafil

cialis tadalafil

cialis at walmart

tadalafil brand names

prednisone 20mg tab watson

what is prednisone 20mg tablets used for

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

http://wrightsregister.com/broker-service/

posologie prednisone 20mg

prednisone 20mg poison ivy

cialis daily prescription

how to order cialis without a prescription

cost tadalafil 20mg – cost cialis 5mg best cialis sites online

order cialis 20mg pills – tadalafil cheap cialis price walmart

cialis prescription coupon

tadalafil without prescription canada

covid antivirals

mulnupiravir

india pharmacy cialis

tadalafil medication

cialis professional

cheapest generic cialis online pharmacy

cialis without prescriptions

cialis without a doctor prescription

order plaquenil generic – plaquenil 400mg tablet order hydroxychloroquine 200mg for sale

cheap generic cialis for sale

INTEGRATING KEYCLOAK’S ACCESS MANAGEMENT SOLUTION WITH A SPRING BOOT APPLICATION

https://www.enerwater.eu/june-2015-press-release-tv-advertising/

ivermectin antiviral

order stromectol online

buy viagra for female online

sildenafil dosage

side effects of prednisone in humans

steroid side effects

can you buy cialis over the counter in usa

ivermectin 12mg without a doctor prescription – ivermectin coronavirus buy oral stromectol

cheap cialis india

cialis without a doctor prescription