A quick guide to use Spring Cloud Gateway with Keycloak

Arvind Pareek
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).
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:
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:
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:
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
xfactrs Launch at the Subscription Insider Show
Ravin Checker and team has launched xfactrs - the most awaited decision intelligence platform for subscription businesses. The event took place at the Subscription Insider Show 22. Here is the transcript from Ravin's presentation. .... Drip. Drip. Drip. That is the...
Are the subscription businesses flying blind?
Kiran MohanThat might be too harsh a question, but a relevant one given what we see in the industry. So, how is your subscription business doing? Are you making the right decisions to grow your business? Chances are might not, optimally. This is because the current...
Potential Revenue Leakage Issues that can Occur Even Before the Sale
Kiran Mohan, Marketing AssuranceSubscription models offer favorable opportunities for both the providers and customers alike, yet it can be a nightmare owing to its inherent complexity. The nature of subscription businesses is that solutions are often customized to...