How to use ReactJS for secure Role Based Access Control

Published by Apoorv Tripathi on November 05, 2024
How to use ReactJS for secure Role Based Access Control

Front-end libraries and frameworks have become essential to the web development stack. React.js is a popular open-source JavaScript library created by Facebook that simplifies building interactive user interfaces. React allows you to create applications by building reusable components, which you may imagine as separate Lego pieces. These components constitute separate segments of a complete interface, which, when put together, become the application's complete user interface. We can handle authorization without any special module or library by using a few utility functions; however, these basic approaches to implementing authorization may not be efficient or effective for even moderately complex applications. Therefore, we will use Cerbos to implement authorization in our application in order to take advantage of the many benefits of modern-day authorization practices.

In this article, we will integrate Cerbos with our example Internal Admin Dashboard application to implement authorization effectively.

  • The Internal Admin Dashboard application is designed to manage user accounts within an organization.
  • Authorization determines if a user can perform specific actions or access certain resources or data. It enables organizations to control access to sensitive databases, private data, and corporate resources.
  • In our ReactJS application, authorization will define what actions are allowed based on roles. Roles are based on four categories of users: Intern, Executive, Manager, and CEO.
  • The manager and the CEO should be authorized to delete an employee's entry from the dashboard.
  • Interns and executives should be granted view-only access to entries from the Internal Admin Dashboard.

Cerbos PDP

We'll use the open source Cerbos Policy Decision Point (PDP) to implement authorization by running it locally as a Docker container. Once the container is operational, we'll establish a communication channel between our application and the Cerbos PDP. This is where authorization decisions are made, with all policies, roles, and access controls defined and checked whenever a user accesses the application. In reality, the PDP can be deployed in various ways: as a cloud instance, a local Docker instance, a local binary, or via Kubernetes. In other words, it is highly flexible.

How RBAC works

The permissions assigned to each role in role based access control (RBAC) provide users with only the access they need to perform their work, no more and no less. This method prevents unauthorized access to sensitive information, reducing the risk of misuse. Permissions in RBAC can be expressed in many ways. Three common categories are:

  • Permission to Modify Resources: This includes the ability to create, edit, or delete resources such as files, database entries, or other types of content within the system. For example, a manager might have permission to update employee records or delete outdated documents.
  • Permission to Access Applications: This determines which applications or systems a user can access. For instance, an executive might have access to financial reporting tools, while an intern might only have access to basic project management software.
  • Permissions Within Applications: These permissions define what actions a user can perform within a given application. For example, within a project management tool, a user might have permission to create new projects, assign tasks, or view reports, depending on their role.

If RBAC is designed and assigned correctly, no further changes should be necessary to a user’s access profile as long as they retain their role. Should their status within the company change—for example, through a promotion to a new role with more responsibilities—permissions would be adjusted to enable them to carry out their new duties.

Examples of Role Based Access Control

RBAC enables organizations to create a variety of roles with permissions that can be assigned to new hires or to users whose responsibilities change over time. For example:

  • Marketing Role: Provides access to the Content Management System (CMS), Google Analytics, and Facebook Ads.
  • Finance Role: Provides access to accounting software and billing systems such as Xero or ADP.
  • Human Resources Role: Provides access to personnel files and HR-related tools such as Oracle Cloud Human Capital Management or Paycor.

The permissions assigned to each role enable the user to perform their job without hindrance. If users do not have access to all the resources necessary to do their work, the policy manager can add permissions to their role or assign them a different role that includes the necessary permissions.

Why you should switch to Authorization-as-a-Service

Effectively managing permissions is crucial for any application developer. Many businesses are switching to Authorization-as-a-Service (or "externalized authorization") for several compelling reasons:

  • Reduced Complexity: Traditional authorization methods can add significant time, cost, and complexity to the development process. Authorization-as-a-Service simplifies this, allowing development teams to focus on core functionalities.
  • Enhanced Security: Centralized control with Cerbos allows for rapid application-wide policy adjustments, eliminating the need for time-consuming code changes.
  • Effortless Compliance: Authorization-as-a-Service integrates compliance rules and regulations, ensuring adherence to standards such as ISO 27001 without additional effort.

Cerbos PDP: open source access control & authorization layer

Cerbos PDP provides an access control layer. This enables you to decouple the authorization mechanism from your core application. This type of Authorization-as-a-Service provides organizations in need of secure and efficient access control with a host of benefits, including:

  • Reduced development time: Defining and implementing authorization is time-consuming. Cerbos offers a standardized solution that is easy to integrate, saving you time and money.
  • Scalability: Cerbos allows scaling organizations to manage increasingly complex authorization schemas without code changes. It supports the growing needs of your business efficiently.
  • Centralized control: Authorization-as-a-Service offers centralized control of your access control policies across multiple applications. Manage permissions and roles—and oversee all authorization activity—from one central platform.
  • Rapid deployment: The Cerbos PDP service can be deployed quickly and is ready to use. Once deployed, you can start configuring the access control mechanisms to suit your particular needs.
  • Real-time monitoring: With Cerbos, you can monitor and audit access activity in real-time. This enables effective enforcement of and compliance with internal policies and regulatory requirements. Generate detailed reports and quickly address unauthorized access attempts.
  • Integration with existing systems: As an HTTP endpoint, Cerbos PDP is language agnostic, allowing seamless integration with the application codebase regardless of the programming language used.

Modelling policies

A 3x5 chart illustrating the relationship of actions and resources

With Cerbos, access rules are resource-oriented, and the policies map to the resources within your system. A resource can be anything, and the way you model policies is up to you. You can achieve the same logical outcome in various ways of access control: action-led, role-led, attribute-led, or with combinations of different access-control mechanisms.

That said, some patterns will lend themselves more naturally to specific scenarios. Let’s look at some different approaches. Consider this permission model:

A graphic showing which roles can perform which actions

Prerequisites

  1. WSL (if Windows is your primary OS)
  2. Docker
  3. npm

Integrating Cerbos in a ReactJS application

  1. To get started, clone this repository and follow along. Make sure you are in the repository's frontend directory.

File structure of our application

A small list of files, displayed in a modern IDE

Now run npm install to install dependencies if needed. To bootstrap or initialize the application, run npm run dev in the frontend directory. Once the build is successful, you should see the web page loading on your browser at localhost:5173.

A table listing a series of users, their email addresses and usernames, and an action that they're not authorised for (respectively)

Now run npm install to install dependencies if needed. To bootstrap or initialize the application, run npm run dev in the frontend directory. Once the build is successful, you should see the web page loading on your browser at localhost:5173.

A screenshot showing an error model resulting from an attempted unauthorised action

Currently, the application has basic permissions hardcoded: managers and CEOs can delete entries from the list, while interns and executives can only view entries and cannot access the delete button. However, because we have not yet integrated Cerbos for permission management, these hardcoded permissions are not enforced. As a result, despite the intended permissions, managers and CEOs are currently unable to delete entries from the list.

After integrating Cerbos, we will ensure that the manager and CEO roles have the correct permissions to delete entries.

To demonstrate, when we select the role of CEO in the admin dashboard, the ability to delete an entry should be present. However, authorization checks will only take effect and grant access once we have set up the Cerbos Docker instance and connected the application to the Cerbos Policy Decision Point (PDP).

Integrating the Cerbos service

To integrate Cerbos into our ReactJS application, we will begin by launching the Cerbos Docker container. In the frontend directory (/internal-admin-cerbos/frontend), run the Docker container.

Command for Mac/Linux users:
docker run --rm --name cerbos -d -v $(pwd)/cerbos/policies:/policies -p 3592:3592 -p 3593:3593 ghcr.io/cerbos/cerbos:0.34.0

Command for Windows (Command Prompt) users:
docker run --rm --name cerbos -d -v %cd%\cerbos\policies:/policies -p 3592:3592 -p 3593:3593 ghcr.io/cerbos/cerbos:0.34.0

Run docker ps to check if the container persists.

Generate policy files with Cerbos RBAC policy generator

Cerbos Playground is a utility for creating and testing policies online. The policy generator tool is a great way to build policies interactively. We can use the RBAC Policy Generator to generate a policy for our ReactJS application.

We have two roles in our application: admin and user.

  • Admin: This role includes CEOs and Managers.
  • User: This role includes Executives and Interns

Generate the policy

  • Use the RBAC Policy Generator to generate a policy for your ReactJS application.
  • Define the actions and select the checkboxes based on the permissions you want to grant to each role. Specify these permissions clearly:
    • Admin: Full access to all resources and actions.
    • User: Restricted access based on their specific roles and responsibilities.

Screenshot of the RBAC policy generator. It's very grey.

Generate the YAML policy file:

  • After selecting the permissions, click the Generate button to create a YAML policy file named users.yaml.

A screenshot from an IDE showing a split-panel. On the left, a file tree. On the right, a YAML file.

  • The policy generator also creates a users_test.yaml file, which helps automate the testing of your access control policies. Ensure this test file ends with the _test suffix.

A screenshot from an IDE showing a split-panel. On the left, a file tree. On the right, a YAML file.

Now that we have integrated Cerbos with the ReactJS application, we will run it to check if the policies are working as expected.

Testing the policy file

Now that the Cerbos policy is integrated with your ReactJS application, it’s time to test it to ensure the policies are working as expected. Follow these steps:

Command for Mac/Linux:

docker run -i -t -v $(pwd)/cerbos/policies:/policies ghcr.io/cerbos/cerbos:latest compile /policies

For Windows Command Prompt:
docker run -i -t -v %cd%\cerbos\policies:/policies ghcr.io/cerbos/cerbos:latest compile /policies

When running this command, the tests are successfully executed.

A docker command

Policies taking effect in the application UI

The interns and executives (having the role: user) will, as expected, not be able to access the delete button—they’ll only be able to view an entry.

Oh there's that list of users and things they can't do again!

The CEO and manager are authorized to delete an entry from the list.

A list of users but this time there's a "delete" button on each line. A mouse pointer hovers over one of those delete buttons.

The entry gets successfully deleted.

THE USER WAS DELETED!

This hands-on demonstration successfully depicts the integration of Cerbos with our ReactJS application.

Frequently Asked Questions

Q. How can we secure API routes in a React JS application using Cerbos?
A. To secure API routes in a React JS application using Cerbos, follow these concise steps:

  1. Deploy Cerbos: Set up the Cerbos policy engine as a standalone service or containerized instance.
  2. Define Policies: Create YAML files to specify role-based access control rules for API actions and resources.
  3. Integrate Cerbos: Incorporate Cerbos checks in your backend API to validate user permissions before processing requests.
  4. Handle Authorization: In your React app, ensure API calls are made with appropriate user credentials and error handling is taken care of.

Q. Can policies be tested using Cerbos before they are live?
A. Yes, policies can be tested before they are live. Cerbos provides robust policy testing capabilities, allowing you to validate your access control rules before deploying them in a production environment. Using Cerbos' testing framework available in the Policy Generator, you can ensure that policies enforce the desired access control rules and avoid potential issues in live scenarios. This pre-deployment testing helps maintain the integrity and security of your access control policies, and ensures compliance with your organization's security guidelines.

Conclusion

You have successfully integrated Cerbos into an internal admin dashboard application through the following steps:

  • Deploying Cerbos in a Docker container to ensure a consistent and isolated environment.
  • Defining policy files for clear access control rules.
  • Integrating these policies into your application code to ensure they are enforced.
  • Verifying that the application adheres to the established authorization rules, ensuring secure and controlled access.

Sign Up to Cerbos Hub

To further streamline your access control, consider Cerbos Hub—a centralized platform where you can manage and deploy your authorization policies across all your PDPs. With Cerbos Hub, you gain:

  • Scalable and secure authorization management.
  • Streamlined policy deployment and monitoring.
  • Advanced tools for policy design and testing.

Sign up now to secure your applications with Cerbos Hub.

Join the Cerbos Community!

Connect with us on the Cerbos Community Slack to share your journey, ask questions, and get support from fellow developers. Together, let's build secure applications and streamline access control.

Explore the Cerbos open-source PDP on GitHub, contribute to the community, and customize the authorization experience to fit your needs.

Book a free Policy Workshop to discuss your requirements and get your first policy written by the Cerbos team