[Practice] - Secure Spring Boot REST APIs using Keycloak
This tutorial walks you through the steps of securing Spring Boot REST APIs using Keycloak.
Keycloak is an open source Identity and Access Management tool that uses standard protocols such as OAuth 2.0, OpenID Connect, and SAML to secure web applications and web services.
In this example, we will build a simple Spring Boot Application and integrate the application with Keycloak to protect the REST APIs from unauthorized calls. You will also learn to create users programmatically in Keycloak, login and generate JWT token to access the secured REST APIs.
Follow the steps below to complete this example:
Set Up Keycloak
The first step will be to download, setup, and run the Keycloak Server. If you have already set up the Keycloak server then continue from step two. Otherwise, go to our Keycloak quickstart tutorial to set up the Keycloak Server for using it with this example.
Create a Spring Boot Application
- Go to Spring Initializr at https://start.spring.io and create a Spring Boot application with details as follows:
- Project: Choose Gradle Project or Maven Project.
- Language: Java
- Spring Boot: Latest stable version of Spring Boot is selected by default. So leave it as is.
- Project Metadata: Provide group name in the Group field. The group name is the id of the project. In Artifact field, provide the name of your project. In the package field, provide package name for your project. Next, select your preferred version of Java that is installed on your computer and is available on your local environment.
- Dependencies: Add dependencies for Spring Web, Spring Boot DevTools, and Spring Security.
Refer to the image below for example:
- Click the GENERATE button and save/download the project zip bundle.
- Extract the project to your preferred working directory.
- Import the project to your preferred Java development IDE such as Eclipse or IntelliJ IDEA.
Add Keycloak Spring Dependencies
Add Keycloak Spring Boot Starter, and Keycloak Admin REST Client dependencies to your application. The Keycloak Spring Boot Starter takes benefit of Spring Boot's auto-configuration and Keycloak Admin REST Client provides Keycloak admin functionalities which will help to create users programmatically in Keycloak.
For Gradle
Add the following dependencies to the build.gradle file:
For Maven
Add the following dependencies to the pom.xml file:
Find the latest version of keycloak-spring-boot-starter in the Maven Repository .
You can find the latest version of Keycloak Admin REST Client in the Maven Repository .
Add Application Configurations
The Keycloak Spring Boot needs some extra configurations which can be added via Spring Boot configuration properties file. Add the following configuration properties in the application.properties file and do not forget to replace the values of server.port, keycloak.realm, keycloak.resource with values that is relevant to your project:
Create a SecurityConfig class
This SecurityConfig class file must extend the KeycloakWebSecurityConfigurerAdapter abstract class. KeycloakWebSecurityConfigurerAdapter is a convenient base class provided by Keycloak for creating a WebSecurityConfigurer instance.
The SecurityConfig class must be annotated with the following annotations:
- @Configuration - This annotation indicates that the class is a configuration class containing bean definitions for the application context.
- @EnableWebSecurity - This annotation indicates that the class is a Spring Security configuration with information telling how to authenticate users. It provides security configuration via HttpSecurity which is provided as a method parameter in a method called configure and allows you to configure accessibility based on the url-patterns, handlers and authentication endpoints.
- @EnableGlobalMethodSecurity(prePostEnabled = true) - This annotation enables Spring Security global method security. The use of prePostEnabled = true enables @PreAuthorize and @PostAuthorize annotations.
- @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) - The @ComponentScan tells Spring to scan the packages assigned to basePackageClasses .
Create a Data Transfer Object
Create a UserDTO.java Java class. This class should only contains getter/setter methods with serialization and deserialization mechanism but should not contain any business logic.
Create a Web Controller
Create a simple web controller with the following REST methods:
- /users/create - to create new users.
- /users/signin - to authenticate and retrieve access token.
- /users/unprotected-data - this method is not protected by Keycloak so anybody can access it.
- /users/protected-data - this method is protected by Keycloak and can be accessed only by using a valid user access token.
To get client secret, login to your Keycloak realm admin console at http://localhost:8080/auth/admin and go to the Clients settings page under the Credentails tab as shown in the image below:
Create keycloakConfigResolver Reference Method
Create a keycloakConfigResolver reference method in the Spring Boot main application class. This method must be annotated with @Bean annotation and also must return an instance of KeycloakSpringBootConfigResolver class. The use of this keycloakConfigResolver reference will make the application to use Spring Boot configuration properties file instead of the Keycloak default keycloak.json file.
Run the Application
Run the application and do the following tests:
1. Sign up/Create a user using POST request via any HTTP requesting Tool as shown in the image below:
2. Retrieve Access token by signing in - Make a sign-in POST request using the email and password of the as shown in the image below:
3. After you received a token in login response. Call the secured REST API. Example shown in the image below:
4. You can also retrieve access token directly from the Keycloak Server
Summary
Congratulations! you have learned how to integrate Spring Boot REST APIs with Keycloak.
Note: When deploying Keycloak in the Production environment, it is recommnended to choose an operating mode between Standalone and Domain mode. In Production environment, you may also need to configure an external shared database like PostgreSQL, MySQL, Oracle for Keycloak storage to run in a cluster and also configure securities such as encryption and https. To learn how to configure Keycloak with MySQL database, we recommend you to read Keycloak with MySQL
No comments:
Post a Comment