A quick guide to use Spring Cloud Gateway with Keycloak

xfactrs

Arvind Pareek

xfactrs Blog Keycloak

Keycloak is an open-source identity and access management solution which provides user federation, strong authentication, user management, fine-grained authorization, and more. In this blog, we will be looking at how we can integrate Keycloak with Spring Cloud Gateway using Open ID Connect (OIDC).

Keycloak

Setup Keycloak

Use the Keycloak docker image, and attach it a specific port. Sample docker-compose yml section is given below.

version: ‘1.0’

services:

Keycloak:

image: quay.io/Keycloak/Keycloak:20.0.01

ports:

– 9040:9040

environment:

– KEYCLOAK_USER=*****

– KEYCLOAK_ADMIN_PASSWORD=*****

Bring up keyclock and go to the admin page http://localhost:9040/admin . Login with admin username and password. This will be same as the ones set with the environment variables – KEYCLOAK_USER and KEYCLOAK_ADMIN_PASSWORD. Proceed to the configuration of realm, client and user as outlined here

Create an Application with Spring Cloud Gateway

Go to https://start.spring.io and create a project with Gateway and 0Auth2 Client. Create a simple rest controller as below:

Keycloak

This will return the ID of the Keycloak user from the principal object, which is created by spring security.

Below security consideration should be there to protect endpoint:

xfactrs Blog 5

Each request is authenticated. If user is not logged in, there will be a redirection to the Keycloak login screen.

Application Properties:

application.yml file if the file should be similar to the below:

xfactrs Blog 4

Set the client Id and client secret key based on what was configured in Keycloak.

With all the above changes, start the application. Going to http://localhost:8080 will see the browser redirect the user to the login page of Keycloak. User can login with username / password.

Relevant Blogs

Who’s your Leak Fighting Champion?

Who’s your Leak Fighting Champion?

Kiran Mohan“I think we should advise our clients to start investing in the new role of Chief Revenue Leakage Detection Officer,” Said our CRO in our weekly staff meeting. In all our conversations with prospects and customers alike, we’ve figured that who in their...