Skip to main content

How to use AccessControl for RBAC and ABAC in Node.js

 System security is one of the key considerations when building software, and there are various mechanisms used in ensuring a software system is secure. The common ones are role-based access control (RBAC) and attribute-based access control (ABAC).


AccessControl, a Node.js module, can be used to implement these two access control mechanisms. Before diving into how AccessControl works, let’s briefly explain these two mechanisms and how they work.


Role-based access control (RBAC)

Role-based access control, also known as role-based security, is a mechanism that restricts system access to users using their roles and privileges and permissions.


Within an application, roles are created for various user types (e.g., writer or reader). The permission to perform certain actions or access application resources are assigned to specific roles. For instance, in a writing application, a writer can be granted the permission to create, update, read, and delete a post, whereas a reader can be restricted to only being able to read a post.


When using RBAC, there are three guiding rules:


Role assignment: A subject (i.e., a user) can exercise a permission only if the subject has selected or been assigned a role.

Role authorization: A subject’s active role must be authorized for the subject. With rule 1 above, this rule ensures that users can take on only roles for which they are authorized.

Permission authorization: A subject can exercise a permission only if the permission is authorized for the subject’s active role. With rules 1 and 2, this rule ensures that users can exercise only permissions for which they are authorized.

A user can have multiple roles and a role can have multiple permissions. RBAC also supports role hierarchy where a high-level role inherits the permissions of its sub roles. Additional constraints may be applied to place restrictive rule on the potential inheritance of permissions from another role. Some examples of constraints are:


A role cannot inherit itself

Cross-inheritance is not allowed (if the writer inherits from the reader, the reader cannot inherit from the writer)

A role cannot pre-extend a non-existing role

Attribute-based access control (ABAC)

Attribute-based access control, also known as policy-based access control for IAM, defines an access control paradigm whereby access rights are granted to users through the use of policies which combine attributes together. The policies can use any type of attributes, such as user attributes, resource attributes, object, and environment attributes.


ABAC can be used to complement RBAC in that in addition to roles and permissions, a policy can be used to define what attribute is allowed or not allowed.


Node.js RBAC-ABAC using AccessControl

AccessControl, a Node.js module, merges the best features of RBAC and ABAC. It implements RBAC basics and also focuses on resource and action attributes. For a full list of the module’s features, view the documentation.


Installation

With npm: npm i accesscontrol --save.

With Yarn: yarn add accesscontrol


Roles

Roles serve as containers for permissions. They are assigned to users depending on their responsibility. You can create and define roles simply by calling .grant(<role>) or .deny(<role>) methods on an AccessControl instance.


import { AccessControl } from 'accesscontrol';


const ac = new AccessControl();

ac.grant('reader');

Roles can extend other roles. You can extend a role by calling .extend on an existing role.


ac.grant('reader').extend('writer');

Actions and action-attributes

Actions and action-attributes represent what can be performed on resources by role(s). They are a finite fixed list based on classic CRUD. There are two action-attributes which define the possession of the resource by a role: own and any.


For example, an editor role can create, read, update or delete (CRUD) any post resource. But a writer role might only read or update its own post resource.


You can define an action and possession on a resource using: createOwn, readOwn, updateOwn, deleteOwn, createAny, readAny, updateAny, and deleteAny methods.


const ac = new AccessControl();

ac.grant('reader')

  .readAny('post')

  .grant('writer')

    .createOwn('post')             

    .deleteOwn('post')

    .readAny('post')

  .grant('editor')                   

    .extend('writer')                 

    .updateAny('post')  

    .deleteAny('post');

Resources and resource-attributes

These represent system elements that we want to protect, such as post. Multiple roles can have access to a specific resource but may not have equal access to all attributes of the resource. You can use Glob notation to define allowed or denied attributes.


For example, we have a post resource that has the following attributes: id, title, and description. All attributes of any post resource can be read by an editor role:


ac.grant('editor').readAny('post', ['*']);

But the id attribute should not be read by a reader role.


ac.grant('reader').readAny('post', ['!id']);

Checking permissions and filtering attributes

The permission granted is determined using a combination of role, action, and resource. You can add .can(<role>).<action>(<resource>) on an AccessControl instance to check for granted permissions for a specific resource and action.


const permission = ac.can('reader').readAny('post');

permission.granted;

permission.attributes;

permission.filter(data);

Defining all grants at once

You can pass the grants directly to the AccessControl constructor. It accepts either an Object:


let grantObjects = {

reader: {

        post: {

            'read:any': ['*', '!id]

        }

    },

    writer: {

        post: {

            'create:own': ['*'],

            'read:any': ['*'],

            'update:own': ['*'],

            'delete:own': ['*']

        }

    },

    editor: {

        post: {

            'create:any': ['*'],

            'read:any': ['*'],

            'update:any': ['*'],

            'delete:any': ['*']

        }

    }

}


const ac = new AccessControl(grantsObject);

Or an array:


let grantArray = [

  { role: 'reader', resource: 'post', action: 'read:any', attributes: '*, !id' },

  { role: 'writer', resource: 'post', action: 'read:any', attributes: '*' },

  { role: 'writer', resource: 'post', action: 'create:own', attributes: '*' },

  { role: 'writer', resource: 'post', action: 'update:own', attributes: '*' },

  { role: 'writer', resource: 'post', action: 'delete:own', attributes: '*' },

  { role: 'editor', resource: 'post', action: 'read:any', attributes: '*' },

  { role: 'editor', resource: 'post', action: 'create:any', attributes: '*' },

  { role: 'editor', resource: 'post', action: 'update:any', attributes: '*' },

  { role: 'editor', resource: 'post', action: 'delete:any', attributes: '*' },

]


const ac = new AccessControl(grantArray);

Example with Express.js

const ac = new AccessControl(grants);


router.get('/posts/:title', function (req, res, next) {

    const permission = ac.can(req.user.role).readAny('post');

    if (permission.granted) {

        Video.find(req.params.title, function (err, data) {

            if (err || !data) return res.status(404).end();

            res.json(permission.filter(data));

        });

    } else {

        res.status(403).end();

    }

});

Conclusion

We have shown how we can use AccessControl for authorization in a server-side application. We can also use it to authorize routes and UI elements in a client-side application, which can be done by using the same grant object for both the server and the client. AccessControl is one only library for implementing access control in Node.js. Node-casbin and CASL are also Node.js libraries for implementing access control.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...