In this video, we will secure a React application with Keycloak security.
But before we begin don’t forget to subscribe to my channel and hit the bell icon to get notified on new video uploads.
Check out the React project in the reference section, or you can create your own React project from scratch using create-react-app. For this demo, we will use the project from Github.
Before running the React application we first need to configure the Keycloak server for security.
Configure the 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.
The React Project
This project is already complex, so I want you to focus on the files inside the framework and api-services folder. I’m using a free React template/layout from Primefaces.
As with most of the React project index.js is the entry point of the application. Here are the most notable files that handle runs the app and handle the security.
- ApplicationStore – Where the store is configured. Here we define both middlewares and enhancers.
- Dispatch – common global action definition
- Reducers – the main reducer file
- Authorization – where keycloak initialization and actions are defined like refresh token, logout, etc.
- Customers – customer action creators and reducers
- SecureLayout – HOC layout template for secure pages
- SecureRoutes – HOC that secures a page
- SecurityContext – this is our React security context
- Customers – secured pages
Running the React Project
- Inside the React project run npm start.
- Navigate to http://localhost:3000, it should open the home component. This is a simple component with a router link to a secured page.
- To secure the page we introduce 2 HOC:
- withSecurity – handles the security, redirects to login page if not authenticated
- withSecureLayout – handles the layout of the secured pages