Using Casbin for user authorization in a system

Using Casbin for user authorization in a system

Daily short news for you
  • Morning news, does everyone remember the lawsuit of Ryan Dahl - or more accurately, the Deno group against Oracle over the name JavaScript?

    Oracle has responded that they are not giving up the name JavaScript 🫣

    https://x.com/deno_land/status/1876728474666217739

    » Read more
  • Are people taking their Tet holidays early or what? Traffic has dropped significantly this whole week 😳. It's a bit sad to talk to myself, so if anyone passes by and reads this, please drop a "comment" for some fun at home. You can say anything since it's anonymous 😇🔥

    » Read more
  • Someone asked me where I get my news so quickly, or how I find so many tools and projects... where do I get all of that? Well, there’s a source far on the horizon but close right in front of you, and that is the Github Trending page.

    This page tracks the repositories that have the most "stars" according to day/week/month. It also allows you to filter by programming language, and each language represents a kind of theme. For example, Python is buzzing about AI, LLMs..., Rust has all the super powerful tools, and Go is... just a continuous plaything 😁. Meanwhile, JavaScript 🫣😑

    » Read more

Problem

Authorization is a feature that appears in many places in software applications. For example, when sharing files on the internet with others, you can give recipients permission to read, download, or edit the content... In management systems like CMS, authorization becomes more essential than ever. Each user should only have access to authorized resources to avoid future troubles.

In the past, when implementing authorization, the simplest way was to use if...else to check a specific attribute, such as the user's role, if it is valid when accessing resources. For example, a user with the role of admin would have the highest privileges in the system, while a mod would have lower privileges. Two functions, checkAdmin and checkMod, were created to quickly check if a user is an admin or mod, and they are called when checking privileges before accessing resource logic.

function checkAdmin(role) {
    if (role === "admin") {
        return true;
    }
    return false;
}

function checkMod(role) {
    if (role === "mod") {
        return true;
    }
    return false;
}

This is only suitable for simple applications that do not require strict authorization. In reality, our applications often require more fine-grained control, for example, a group of mod users has read/write access to specific APIs. Sometimes, we also need to build a user permission management page, where users, actions, and allowed resources are carefully set.

I believe there are many ways to implement authorization, and it varies depending on the specific case of each system. Therefore, the maintenance problem needs to be considered. If starting from scratch for authorization implementation is not good or difficult to understand and extend, it will take more time for modifications and upgrades. On the contrary, when we have a common voice, the ability to access the problem will be significantly faster.

Casbin is an open-source access control library that provides support for enforcement authorization based on various access control models. Casbin supports and implements popular authorization models in multiple programming languages. In other words, it simply simplifies your code for authorization issues.

Types of access control

There are many ways to control access, not to mention their customization to fit various problems in each application. However, generally speaking, we have three popular approaches: ACL, RBAC, and ABAC.

ACL stands for Access Control List, which means mapping users to actions on resources.

Before proceeding, there are three basic concepts for access control that are the subject (sub), resource (obj), and action (act) involved in controlling access.

Returning to the first example, a mod has the privilege to add/edit/delete articles. At this time, the article is the obj, the action add/edit/delete is the act, and mod is the sub. This is a typical example of ACL.

A bit more complex, we have RBAC, which stands for Role-Based Access Control.

RBAC is similar to ACL in terms of permissions and resources allowed to be accessed. However, instead of assigning permissions directly to an end user, it creates an intermediate object called a "role," and users who have a specific "role" will have the permissions of that role.

For example, mod has the privilege to add/edit/delete articles, and hoaitx is a user in the system with the "role" of mod, so hoaitx has the privilege to add/edit/delete articles.

Another common model is attribute-based access control (ABAC). ABAC is similar to RBAC, but instead of managing permissions based on "roles," ABAC manages permissions based on attributes. This means that an object has access based on the attributes it possesses. For example, if the user hoaitx is assigned the attribute read_article and has the permission to read articles, then hoaitx also has the permission to read articles.

Implementation in practice

Before implementing, let's take some time to understand how Casbin works, as understanding it will help you get acquainted with this authorization model more quickly.

In Casbin, the access control model is abstracted into a CONF file based on the PERM meta-model. The PERM model consists of four platforms: Policy, Effect, Request, and Matchers. These platforms describe the relationship between resources and users.

To learn more about these four platforms, readers can refer to How It Works - Casbin.

The CONF files define the ACL, RBAC, ABAC authorization models... You can create your own configuration or use the existing templates provided by Casbin. For example, a file used for ACL may look like this:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

Next, we need a file that defines the values of sub, obj, act... as mentioned earlier, aiming to specify what permissions the object has regarding which resource. These files are called "policy" files.

For example, an ACL policy file may look like this:

p, hoaitx, article, read
p, hoaitx, article, write

Then, use these two files in the code to check authorization conditions. For example, when implementing with Node.js, first install the casbin module:

$ npm i casbin

Then use:

import { newEnforcer } from 'casbin';

const e = await newEnforcer('path/to/model.conf', 'path/to/policy.csv');

With path/to/model.conf being the path to the CONF file, and path/to/policy.csv being the path to the policy file you just created.

After that, checking if the user hoaitx has the read permission for the article resource is straightforward:

const sub = 'hoaitx';
const obj = 'article';
const act = 'read';

if ((await e.enforce(sub, obj, act)) === true) {
    // permit
} else {
    // deny
}

That's just a basic example, Casbin provides many advanced authorization models, powerful APIs like flexible policy management or support for storing, updating CONF files in various ways. Readers can learn more at API Overview and Model Storage, or start with Casbin's official documentation: Overview.

Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...
Scroll or click to go to the next page