Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Easily secure your Spring Boot applications with Keycloak

May 25, 2017
Sebastien Blanc
Related topics:
JavaSpring BootSecurity
Related products:
Red Hat support for Spring Boot

Share:

    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:

    ./standalone.sh(bat)
    

    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":

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

    Now we need a controller:

    @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 {
          request.logout();
          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:

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

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

    <#import "/spring.ftl" as spring>
    <html>
    <h1>My products</h1>
    <ul>
    <#list products as product>
        <li>${product}</li>
    </#list>
    </ul>
    <p>
        <a href="/logout">Logout</a>
    </p>
    </html>

    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 application.properties.

    Defining Keycloak's configuration

    Some properties are mandatory:

    keycloak.auth-server-url=http://localhost:8080/auth
    keycloak.realm=springboot
    keycloak.public-client=true
    keycloak.resource=product-app

    Then we need to define some Security constraints as you will do with a Java EE app in your web.xml:

    keycloak.security-constraints[0].authRoles[0]=user
    keycloak.security-constraints[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:

    server.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:

    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:

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    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:

    @Configuration
    @EnableWebSecurity
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
     class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
    {
       /**
        * Registers the KeycloakAuthenticationProvider with the authentication manager.
        */
       @Autowired
       public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
          keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
          auth.authenticationProvider(keycloakAuthenticationProvider);
       }
    
       @Bean
       public KeycloakConfigResolver KeycloakConfigResolver() {
          return new KeycloakSpringBootConfigResolver();
       }
    
       /**
        * Defines the session authentication strategy.
        */
       @Bean
       @Override
       protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
          return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
       }
    
       @Override
       protected void configure(HttpSecurity http) throws Exception
       {
          super.configure(http);
          http
                .authorizeRequests()
                .antMatchers("/products*").hasRole("user")
                .anyRequest().permitAll();
       }
    }
    

    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 application.properties file and let's add another property to map the Principal name with our Keycloak username:

    keycloak.principal-attribute=preferred_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("principal",principal);
       model.addAttribute("products", productService.getProducts());
       return "products";
    }

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

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

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

    Conclusion

    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.

    Resources

    • Github Project
    • Keycloak website
    • Spring Boot Keycloak Adapter Documentation
    • Spring Security Keycloak Adapter Documentation
    • Spring Initializr Site

     


    For a framework for building enterprise Java microservices visit WildFly Swarm and download the cheat sheet.

    Last updated: February 22, 2024

    Recent Posts

    • Ollama or vLLM? How to choose the right LLM serving tool for your use case

    • How to build a Model-as-a-Service platform

    • How Quarkus works with OpenTelemetry on OpenShift

    • Our top 10 articles of 2025 (so far)

    • The benefits of auto-merging GitHub and GitLab repositories

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue