Monday, 29 May 2017

Easily secure your Spring Boot applications with Keycloak

What is Keycloak?

Although security is a crucial aspect of any application, its implementation can be difficult. Worse, it is often neglected, poorly implemented and intrusive in the code. But lately, security servers have appeared which allow for outsourcing and delegating all the authentication and authorization aspects. Of these servers, one of the most promising is Keycloak, open-source, flexible, and agnostic of any technology, it is easily deployable/adaptable in its own infrastructure. Moreover, Keycloak is more than just an authentication server, it also provides a complete Identity Management system, user federation for third parties like LDAP and a lot more ... Check it out on here. The project can also be found on Github

Spring Boot and Keycloak

Keycloak provides adapters for an application that needs to interact with a Keycloak instance. There are adapters for WildFly/EAP, NodeJS, Javascript and of course for Spring Boot.

Setting up a Keycloak server

You have different options to set up a Keycloak server but the easiest one is probably to grab a standalone distribution, unzip it and voila! Open a terminal and go to your unzipped Keycloak server and from the bin directory simply run:
Then open a browser and go to http://localhost:8080/auth. Since it's the first time that the server runs you will have to create an admin user, so let's create an admin user with admin as username and admin for the password:


Now you can log in into your administration console and start configuring Keycloak.

Creating a new Realm

Keycloak defines the concept of a realm in which you will define your clients, which in Keycloak terminology means an application that will be secured by Keycloak, it can be a Web App, a Java EE backend, a Spring Boot etc. So let's create a new realm by simply clicking the "Add realm" button:


Let's call it "SpringBoot".

Creating the client, the role, and the user

Now we need to define a client, which will be our Spring Boot app. Go to the "Clients" section and click the "create" button. We will call our client "product-app":


On the next screen, we can keep the defaults settings but just need to enter a valid redirect URL that Keycloak will use once the user is authenticated. Put as value: "http://localhost:8081/*"


Don't forget to Save! Now, we will define a role that will be assigned to our users, let's create a simple role called "user":


And at last but not least let's create a user, only the username property is needed, let's call him "testuser":


And finally, we need to set his credentials, so go to the credentials tab of your user and choose a password, I will be using "password" for the rest of this article, make sure to turn off the "Temporary" flag unless you want the user to have to change his password the first time he authenticates. Now proceed to the "Role Mappings" tab and assign the role "user":


We are done for now with the Keycloak server configuration and we can start building our Spring Boot App!

Creating a simple app

Let's create a simple Spring Boot application, you might want to use the Spring Initializr and choose the following options:
  • Web
  • Freemarker
  • Keycloak
Name your app "product-app" and download the generated project:


Import the application in your favorite IDE, I will be using IntelliJ. Our app will be simple and will contain only 2 pages:
  • An index.html which will be the landing page containing just a link to the product page.
  • Products.ftl which will be our product page template and will be only accessible for authenticated user.
Let's start by creating in simple index.html file in "/src/resources/static":

    <title>My awesome landing page</title>
   <h1>Landing page</h1>
   <a href="/products">My products</a>

Now we need a controller:

class ProductController {

   @Autowired ProductService productService;

   @GetMapping(path = "/products")
   public String getProducts(Model model){
      model.addAttribute("products", productService.getProducts());
      return "products";

   @GetMapping(path = "/logout")
   public String logout(HttpServletRequest request) throws ServletException {
      return "/";

As you can see, it's simple; we define a mapping for the product page and one for the logout action. You will also notice that we are calling a "ProductService" that will return a list of strings that will put in our Spring MVC Model object, so let's create that service:

class ProductService {
   public List<String> getProducts() {
      return Arrays.asList("iPad","iPod","iPhone");

We also need to create the product.ftl template, create this file in "src/resources/templates":

<#import "/spring.ftl" as spring>
<h1>My products</h1>
<#list products as product>
    <a href="/logout">Logout</a>

Here we simply iterate through the list of products that are in our Spring MVC Model object and we add a link to log out from our application.

All that is the left is adding some keycloak properties in our

Defining Keycloak's configuration

Some properties are mandatory:


Then we need to define some Security constraints as you will do with a Java EE app in your web.xml:[0].authRoles[0]=user[0].securityCollections[0].patterns[0]=/products/*
Here, we simply define that every request to /products/* should be done with an authenticated user and that this user should have the role "user". One last property is to make sure our application will be running on port 8081:


We are all set and we can run our app!

You have several options to run your Spring Boot application, with Maven you can simply do:

mvn clean spring-boot:run

Now browse to "http://localhost:8080" and you should see the landing page, click the "products" links and you will be redirected to the Keycloak login page:


Login with our user "testuser/password" and should be redirected back to your product page:


Congratulations! You have secured your first Spring Boot app with Keycloak. Now Log out and go back to the Keycloak administration console and discover how you can "tune" your login page. For instance, you can activate the "Remember Me", the "User Registration", hit the save button and go back to your login screen, you will see that these features have been added.

Introducing Spring Security support

If you're a Spring user and have been playing around security, there is a big chance that you have been using Spring Security. Well, I have some good news: we also have a Keycloak Spring Security Adapter and it's already included in our Spring Boot Keycloak Starter. Let's see how we can leverage Spring Security together with Keycloak.

Adding Spring Security Starter

First, we need the Spring Security libraries, the easiest way to do that is to add the spring-boot-starter-security artifact in your pom.xml:


Creating a SecurityConfig class

Like any other project that is secured with Spring Security, a configuration class extending WebSecurityConfigurerAdapter is needed. Keycloak provides its own subclass that you can again subclass:

@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
 class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
    * Registers the KeycloakAuthenticationProvider with the authentication manager.
   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
      keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());

   public KeycloakConfigResolver KeycloakConfigResolver() {
      return new KeycloakSpringBootConfigResolver();

    * Defines the session authentication strategy.
   protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
      return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());

   protected void configure(HttpSecurity http) throws Exception

Let's have a closer look at the most important methods:

  • configureGlobal: Here we change the Granted Authority Mapper, by default in Spring Security, roles are prefixed with ROLE_, we could change that in our Realm configuration but it could be confusing for other applications that do not know this convention, so here we assign a SimpleAuthorityMapper that will make sure no prefix is added.
  • keycloakConfigResolver: By default, the Keycloak Spring Security Adapter will look up for a file named keycloak.json present on your classpath. But here we want to leverage the Spring Boot properties file support.
  • configure: Here is where we define our security constraints, pretty simple to understand we secure the path "/products" with role "user"
Now we can remove the security constraints that we had defined previously in our file and let's add another property to map the Principal name with our Keycloak username:
Now we can even inject the principal in our controller method and put the username in the Spring MVC model:

@GetMapping(path = "/products")
public String getProducts(Principal principal, Model model){
   model.addAttribute("products", productService.getProducts());
   return "products";

Finally, we update the product.ftl template to print out the username:

<#import "/spring.ftl" as spring>
<h1>Hello ${principal.getName()}</h1>
<#list products as product>
    <a href="/logout">Logout</a>

Restart your app, authenticate again, it should still work and you should also able to see your username printed on the product page:


We saw in this article how to deploy and configure a Keycloak Server and then secure a Spring Boot app, first by using Java EE security constraints and then by integrating Spring Security. In the next article, we will decompose this monolith application, which will give us the opportunity to:
  • See how to secure a microservice.
  • How microservices can securely "talk" to each other.
  • How a Pure Web App build with AngularJS can be secured with Keycloak and call secured microservices.


This article is also available in "screencast" format :




  1. I recently built a spring boot application with REST services secured by Keycloak and the Spring Boot Keycloak adapter. I had my security constraints configured in the Everything works fine.

    However in my JUnit tests of the REST service where I inject MockMvc, my REST service is not secured. I inject MockMvc like follows:
    private MockMvc mvc;

    The problem is that inside my REST service I access data (i.e. userName) from the logged in security principle and since with the JUnit test the service is not secured the principle is null.

    Could we perhaps have an example of a secured Spring Boot resource in a JUnit test in a follow up article or the Keycloak documentation?

    If I find a solution I will also report back on this issue.

  2. Hi Sebastien Blanc ,
    I am trying SpringBoot application with SAML2 SSO using keycloak version 3.1.0 final.
    I have created a client application with SAML protocol, generated keystore.jks from keys and downloaded the saml metadata IDPSSODescriptor. In WebSecurityConfigurerAdapter passed the keystore.jks and metadata.xml.
    Upon hitting the url it is reaching to keycloak but throwing error "Unknown login requester" on UI and below is the error in keycloak server log - "type=LOGIN_ERROR, realmId=spring-demo, clientId=https://localhost:8443/saml/metadata, userId=null, ipAddress=, error=client_not_found".

    Kindly suggest where I am doing wrong. Your suggestion will be highly appreciated.


  3. Spring Boot 2.0.0.M1 is out and is not compatible with the keycloak-spring-boot-adapter. Any indication when keycloak will support Spring Boot 2, or do we wait until its final release ?

    thanks !

    There's 4 lines of code in which need to use the new TomcatServletWebServerFactory class in place of the existing TomcatEmbeddedServletContainerFactory.

    As per Spring Boot 2.0.0.M1 release notes:
    Embedded containers package structure

    In order to support reactive use cases, the embedded containers package structure has been refactored quite extensively. EmbeddedServletContainer has been renamed to WebServer and the org.springframework.boot.context.embedded package has been relocated to org.springframework.boot.web.embedded. For instance, if you were customizing the embedded Tomcat container using the TomcatEmbeddedServletContainerFactory callback interface, you should now use TomcatServletWebServerFactory.

  4. Hi Sebastien,

    Thanks and congratulatios for this post.

    Can you recommend me some document about KeyCloakRestTemplate?

    In advance thanks

  5. Exception:
    There was an unexpected error (type=Internal Server Error, status=500).
    Circular view path [products]: would dispatch back to the current handler URL [/products] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

    Rename product.ftl -> products.ftl

  6. The stated example is NOT working in chrome (but seems to work fine in firefox)

    Chrome Version 59.0.3071.115 says:

    Whitelabel Error Page

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    Wed Jul 12 15:20:24 IST 2017
    There was an unexpected error (type=Forbidden, status=403).
    No message available

  7. After following the example, I still get a NullPointerException at model.addAttribute("username", principal.getName());
    Can you please provide a solution?

  8. How do I disable the security in Test
    I already added below 3 lines to my test

    # Keycloak
    keycloak.enabled = false

    Still getting Error 500 .. I am using



Please only add comments directly associated with the post. For general questions use the Keycloak user mailing list.