This video is a companion of my previous blog which secures a React application via keycloak and is available at https://czetsuya-tech.blogspot.com/2019/08/how-to-secure-react-app-with-keycloak.html.
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
- 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.
- 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.
- Make sure that the primereact-client is set to accessType=confidential.
- Check that the keycloak.json in the react project matches the primereact-client, specially the credential secret.
- Import the users in the same folder. It should import 3 users: kerri, admin, and norole.
Configure the Spring Project
- Check out the Spring project from Github.
- Configure Keycloak.
- Via application.yml – we will be using this.
- Via keycloak.json
- Add keycloak-spring-boot-starter dependency in the project’s pom to secure the project with Keycloak.
- Override the class KeycloakWebSecurityConfigurerAdapter.
- Security constraints can be configured via
- KeycloakWebSecurityConfigurerAdapter class
- 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:
- User kerri
- Role user – ok
- Role admin – ko
- User admin
- Role user – ok
- Role admin – ok