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...
https://www.czetsuyatech.com/2019/08/spring-rest-security-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
- application.yml
- KeycloakWebSecurityConfigurerAdapter class
- PreAuthorize annotation
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
References
- https://czetsuya-tech.blogspot.com/2019/08/how-to-secure-react-app-with-keycloak.html
- https://github.com/czetsuya/keycloak-react
- https://github.com/czetsuya/Spring-Keycloak-with-REST-API
- https://github.com/facebook/create-react-app
- https://www.keycloak.org/downloads.html
- https://www.keycloak.org/docs/latest/securing_apps/index.html
Post a Comment