SpringBoot OAuth2 with Keycloak as provider
--
Keycloak is an open-source Identity and Access Management (IAM) solution aimed at modern applications and services. Keycloak provides out-of-the-box authentication and authorization services as well as advanced features like User Federation, Identity Brokering, and Social Login.
To Secure SpringBoot app with Keycloak we can use Keycloak SpringBoot adapter JAR as dependency and provide some configurations in
application.properties, you can find more info about using spring-boot-adapter in Keycloak Docs.
For long time Spring Security provides support for OAuth 2.0 and OpenID Connect. We can also use Spring Boot OAuth2 for securing Spring Boot applications with Keycloak. For better integration with Spring security, it is recommended to use Spring OAuth2 for Keycloak integration.
In this article we will see how to use spring-secuity-oauth2-client to integrate SpringBoot application with Keycloak. As shown in the below sequence diagram, we will be demonstrating steps 1 to 8 in this SpringBoot OAuth2 Keycloak integration
Spring Boot and Keycloak
We will be usingspring-security-oauth2-client
oauth client library to auto configure our SprinBoot application for integration with Keycloak as a OpenId connect provider.
We will be writing a simple SpringBoot application having Thymeleaf UI with just index page. Our application will display client details and logged-in user information, once user is authenticated using Keycloak. If User is not logged-it will be redirected to keycloak login page.
Before looking at application we will setup Keycloak Server and then configure it.
Set Up Keycloak
Download Keycloak from here, unzip, and start using the following command:
./kc.sh(bat) start-dev
Note: Used Keycloak.X which is a Preview distribution powered by Quarkus.
In your browser, go to http://localhost:8080
Since it’s the first time that the Keycloak server is running, you will have to create an admin user, so let’s create an admin user with admin
as the username.