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

  1. Go to Spring Initializr at 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:

  2. Click the GENERATE button and save/download the project zip bundle.
  3. Extract the project to your preferred working directory.
  4. 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:


implementation group: 'org.keycloak', name: 'keycloak-spring-boot-starter', version: '21.0.1'
implementation group: 'org.keycloak', name: 'keycloak-admin-client', version: '21.0.1'

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 file and do not forget to replace the values of server.port, keycloak.realm, keycloak.resource with values that is relevant to your project:


#port for the application to run
server.port = 8081
keycloak.realm = tutorialsbuddy-example
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
#keycloak resource is the client ID
keycloak.resource = tutorialsbuddy-app
keycloak.use-resource-role-mappings = true
#The line below will prevent redirect to login page
keycloak.bearer-only: true

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 .

package com.example.keycloak.config;

import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter;
import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
import org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter;
import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

	protected void configure(HttpSecurity http) throws Exception {




	protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {

		 * Returning NullAuthenticatedSessionStrategy means app will not remember
		 * session

		return new NullAuthenticatedSessionStrategy();

	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();

		keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());


	public FilterRegistrationBean<?> keycloakAuthenticationProcessingFilterRegistrationBean(
			KeycloakAuthenticationProcessingFilter filter) {

		FilterRegistrationBean<?> registrationBean = new FilterRegistrationBean<>(filter);

		return registrationBean;

	public FilterRegistrationBean<?> keycloakPreAuthActionsFilterRegistrationBean(KeycloakPreAuthActionsFilter filter) {

		FilterRegistrationBean<?> registrationBean = new FilterRegistrationBean<>(filter);
		return registrationBean;

	public FilterRegistrationBean<?> keycloakAuthenticatedActionsFilterBean(KeycloakAuthenticatedActionsFilter filter) {

		FilterRegistrationBean<?> registrationBean = new FilterRegistrationBean<>(filter);

		return registrationBean;

	public FilterRegistrationBean<?> keycloakSecurityContextRequestFilterBean(
			KeycloakSecurityContextRequestFilter filter) {

		FilterRegistrationBean<?> registrationBean = new FilterRegistrationBean<>(filter);


		return registrationBean;

	protected HttpSessionManager httpSessionManager() {
		return new HttpSessionManager();

Create a Data Transfer Object

Create a Java class. This class should only contains getter/setter methods with serialization and deserialization mechanism but should not contain any business logic.


package com.example.keycloak.dto;

public class UserDTO {
	private String email;
	private String password;
	private String firstname;
	private String lastname;
	private int statusCode;
	private String status;

	public String getEmail() {
		return email;

	public void setEmail(String email) { = email;

	public String getPassword() {
		return password;

	public void setPassword(String password) {
		this.password = password;

	public String getFirstname() {
		return firstname;

	public void setFirstname(String firstname) {
		this.firstname = firstname;

	public String getLastname() {
		return lastname;

	public void setLastname(String lastname) {
		this.lastname = lastname;

	public int getStatusCode() {
		return statusCode;

	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;

	public String getStatus() {
		return status;

	public void setStatus(String status) {
		this.status = status;


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.

package com.example.keycloak.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.example.keycloak.dto.UserDTO;
import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.CreatedResponseUtil;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.authorization.client.AuthzClient;
import org.keycloak.authorization.client.Configuration;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping(value = "/users")
public class UserController {
	private static final Logger log = LoggerFactory.getLogger(UserController.class);

	private String authServerUrl = "http://localhost:8080/auth";
	private String realm = "tutorialsbuddy-realm";
	private String clientId = "tutorialsbuddy-client";
	private String role = "student";
	// Get client secret from the Keycloak admin console (in the credential tab)
	private String clientSecret = "7b768120-ef4e-4100-8c99-85bb9d4dc5c3";

	@PostMapping(path = "/create")
	public ResponseEntity<?> createUser(@RequestBody  UserDTO userDTO) {

		Keycloak keycloak = KeycloakBuilder.builder().serverUrl(authServerUrl).grantType(OAuth2Constants.PASSWORD)
				.resteasyClient(new ResteasyClientBuilderImpl().connectionPoolSize(10).build()).build();


		UserRepresentation user = new UserRepresentation();

		// Get realm
		RealmResource realmResource = keycloak.realm(realm);
		UsersResource usersRessource = realmResource.users();

		Response response = usersRessource.create(user);


		if (response.getStatus() == 201) {

			String userId = CreatedResponseUtil.getCreatedId(response);"Created userId {}", userId);

			// create password credential
			CredentialRepresentation passwordCred = new CredentialRepresentation();

			UserResource userResource = usersRessource.get(userId);

			// Set password credential

			// Get realm role student
			RoleRepresentation realmRoleUser = realmResource.roles().get(role).toRepresentation();

			// Assign realm role student to user
		return ResponseEntity.ok(userDTO);

	@PostMapping(path = "/signin")
	public ResponseEntity<?> signin(@RequestBody  UserDTO userDTO) {

		Map<String, Object> clientCredentials = new HashMap<>();
		clientCredentials.put("secret", clientSecret);
		clientCredentials.put("grant_type", "password");

		Configuration configuration = new Configuration(authServerUrl, realm, clientId, clientCredentials, null);
		AuthzClient authzClient = AuthzClient.create(configuration);

		AccessTokenResponse response = authzClient.obtainAccessToken(userDTO.getEmail(), userDTO.getPassword());

		return ResponseEntity.ok(response);

	@GetMapping(value = "/unprotected-data")
	public String getName() {
		return "Hello, this api is not protected.";

	@GetMapping(value = "/protected-data")
	public String getEmail() {
		return "Hello, this api is protected.";


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.


package com.example.keycloak;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

public class KeycloakSpringBootRestApiApplication {

	public static void main(String[] args) {, args);

	// Creating bean keycloakConfigResolver
	public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
		return new KeycloakSpringBootConfigResolver();

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


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