Securing Spring Boot Rest Api With Keycloak

This video is a companion of my previous blog which secures a React application via keycloak and is available at https://czetsuya-tech.blo...

This video is a companion of my previous blog which secures a React application via keycloak and is available at

Before we begin, don’t forget to subscribe to my channel and hit the bell icon to get notified on my new video uploads.

Needless to say, we need to set up and run the React project, before we can experiment on this one. So please go over to the previous article.

At this point, I assume that you already have a running and configured Keycloak in docker as well as the React project.

Configure Keycloak Server

  1. Run Keycloak on terminal docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin jboss/keycloak. Note that I’m running my instance on another machine thus I’ll be using a network IP.
  2. Import the realm configuration as well as the users from the Spring Keycloak with REST API project, config folder. See reference below for the link.
  3. Make sure that the primereact-client is set to accessType=confidential.
  4. Check that the keycloak.json in the react project matches the primereact-client, specially the credential secret.
  5. Import the users in the same folder. It should import 3 users: kerri, admin, and norole.

Configure the Spring Project

  1. Check out the Spring project from Github.
  2. Configure Keycloak.
    1. Via application.yml - we will be using this.
    2. Via keycloak.json
  3. Add keycloak-spring-boot-starter dependency in the project’s pom to secure the project with Keycloak.
  4. Override the class KeycloakWebSecurityConfigurerAdapter.
  5. Security constraints can be configured via
    1. application.yml
    2. KeycloakWebSecurityConfigurerAdapter class
    3. PreAuthorize annotation
Let’s run the application, log in and it should navigate us to http://localhost:3000/customers. In this page, we should be able to fetch the list of customers.

To test the role constraints the following users should yield these results. These can be observed using the firebug plugin in firefox:
  1. User kerri
    1. Role user - ok
    2. Role admin - ko
  2. User admin
    1. Role user - ok
    2. Role admin - ok



spring-rest 1465801374676152012

Post a Comment Default Comments