Express
Express

Authorization for Express applications

Implement fine-grained roles and permissions for Express with Cerbos

Client SDK Example

if (user.email.includes("@mycompany.com") ||
  (user.company.package === "premium" && user.groups.includes("managers"))
) {
  if(user.region === resource.region) {
    // access allowed
    AuditLog.record("ALLOWED", "edit", user, resource);
  } else {
    // access denied
    AuditLog.record("DENIED", "edit", user, resource);
  }
} else {
  // access denied
  AuditLog.record("DENIED", "edit", user, resource);
}
if (await cerbos.isAllowed({ principal: user, resource, action: "edit" })) {
  // allowed
} 

Before

After

Building fine-grained access control for an Express app

Express is an open source server environment popular for creating Node.js applications. Cerbos is an open source, self-hosted, authorization service for implementing roles and permissions. Integrating Cerbos with Express has the following benefits:

  1. Open-source community
    Both Cerbos and Express are open-source and each has its own thriving community full of dedicated contributors. Whether you need help with integration, up-scaling, or troubleshooting you’ll find it in either the Cerbos or Express community.
  2. Fine-grained policies
    Configure ABAC, RBAC, row-level, and context-aware access policies. And enforce access control at the API level, thereby providing greater security for key resources.
  3. Flexible customization
    You can use Cerbos to create custom access control rules specific to the functionality of your application. In a multi-tenant environment, you can make access control customizable to different tenants’ requirements. This is not usually possible with the average Node.js application but is relatively simple to achieve when you integrate Cerbos with Express.
  4. Wide-ranging compatibility
    Both Cerbos and Express are well-suited for distributed or stratified architectures. When you integrate Cerbos with Express you ensure consistent access control between microservices.
  5. Transparency and control
    Cerbos provides detailed audit trails of every access request and every policy update, to help you investigate security incidents and enhance compliance with regulations.

How to integrate Cerbos with an Express server


Follow these steps to implement Cerbos in your Express application: on:

Step 1: Install the Cerbos policy decision point and client library

Cerbos binaries are available for various operating systems and architectures. For a list of all available downloads, please visit our releases page on GitHub. It is common to use Docker to run the Cerbos in a container.


Step 2: Install the Cerbos SDK for Javascript

Available here.


Step 3: Initialize the Cerbos client in Express

Then your application can send access control requests to the Cerbos server.

authorization for an express application

Step 4: Sign in to Cerbos Hub (optional)

Signing up to Cerbos Hub is free and makes it easier to work collaboratively on authorization with teammates and centralize authorization management. When you sign up you will be prompted to create an organization and a workspace, to which you will connect a Github repository.


Step 5: Build roles and permissions

Before your Express application is able to enforce access control policies you will need to define those policies in Cerbos. If you signed up to Cerbos Hub there are built-in tools to help you write and test your policies. You can also create your own policy repository. Cerbos policies are written in YAML, and define the principals, resources, and configuration associated with your authorization logic.


Step 6: Integrate Cerbos with your Node.js application

Replace the authorization logic in your Node.js app with a call to Cerbos.

Find a full tutorial here.



Code Examples for a Cerbos Integration with Express

The code below demonstrates how to setup the Cerbos SDK and check permissions inside a GET Express handler.

import express from "express";
import { GRPC as Cerbos } from "@cerbos/grpc";

// Connect to the Cerbos PDP Instance
const cerbos = new Cerbos("localhost:3592");
const app = express();

app.get("/expenses/:id", async (req, res) => {
  // Get the resource from the DB
  const result = expenses.find((expense) => expense.id === req.params.id);
  if (!result) return res.status(404).json({ error: "Expense not found" });

  // Pass the user (principal) and the resource to 
  // Cerbos along with the action to perform
  const decision = await cerbos.checkResource({
    principal: {
      id: req.user.id,
      roles: req.user.roles,
      attributes: req.user
    }
    resource: {
      kind: "expense",
      id: result.id,
      attributes: {
        ...result,
      }
    },
    actions: ["view"],
  });

  // Check whether a particular action is allowed
  if (decision.isAllowed("view")) {
    return res.json(result);
  } else {
    return res.status(401).json({ error: "Unauthorized" });
  }
});


What is Cerbos?

Cerbos is open source, decoupled access control for your application enabling you to implement fine-grained permissions in minutes.

Agile

Define and evolve complex policies without requiring a release cycle

Compliance

Meet your compliance requirements with a full audit trail of policies, permissions, access to resources

Enterprise

Be enterprise ready and meet your customer's organizational requirements with ease

Proactive

Coming soon: SIEM integrations and anomaly detection and recommendations of policy changes

image

Extend Express Roles

Fine grained access controls extending the roles defined in Express

image

Enrich with Context

Request time attribute based authorization enables more contextual access controls

image

Avoid Token Bloat

Independent authorization logic avoids bloated tokens and workarounds

Why Cerbos?

image

Simple

Define access policies using human-readable YAML. No need to master a new policy language.

image

Super-charged Roles

Dynamically derive new roles based on contextual information. Don't be limited to what your IdP provides.

image

Context-aware

Make use of context such as IP address and time of day to make realtime access decisions

image

Ultrafast API

Access decisions in milliseconds.

image

GitOps

Develop, test, and deploy policies just as you do with your source code.

image

Multiple Environments

Built-in policy versioning to support canary deployments and different environments.

image

Cloud Native

Containerised deployment as a microservice or a sidecar. REST and gRPC interfaces. Top-notch observability.

image

Audit Logs

Capture every decision and analyze them later.

image

Community

Leverage our community for examples and help.

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