no

How to Secure a React App With Keycloak

In this video, we will secure a React application with Keycloak security. But before we begin don’t forget to subscribe to my channel an...

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

  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.

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.
  1. framework
    1. redux
      1. ApplicationStore - Where the store is configured. Here we define both middlewares and enhancers.
      2. Dispatch - common global action definition
      3. Reducers - the main reducer file
      4. modules
        1. Authorization - where keycloak initialization and actions are defined like refresh token, logout, etc.
        2. Customers - customer action creators and reducers
  2. pages
    1. layout
      1. SecureLayout - HOC layout template for secure pages
    2. routing
      1. SecureRoutes - HOC that secures a page
      2. SecurityContext - this is our React security context
    3. secure
      1. Customers - secured pages

Running the React Project

  1. Inside the React project run npm start.
  2. Navigate to http://localhost:3000, it should open the home component. This is a simple component with a router link to a secured page.
  3. To secure the page we introduce 2 HOC:
    1. withSecurity - handles the security, redirects to login page if not authenticated
    2. withSecureLayout - handles the layout of the secured pages

References

Related

react 3472454610540230573

Post a Comment Default Comments

item