Using Casbin for user authorization in a system

Using Casbin for user authorization in a system

Daily short news for you
  • Thank you to threads.net from Meta for being the inspiration behind this section on my blog. Initially, I was a bit skeptical about whether creating short posts like this would attract users, whether anyone would come back to read day after day, or if it would all just be like building sandcastles by the sea. As I have often mentioned, creating a feature is not difficult, but how to operate it effectively is what truly matters.

    Now, time has proven everything. The Short Posts section consistently ranks in the top 5 most visited pages of the day/week/month. This means that readers have developed a habit of returning more often. How can I be so sure? Because this section is almost completely unoptimized for SEO on search engines like Google.

    Let me take you back a bit. In the beginning, I was very diligent in posting on threads.net in the hope of attracting many followers, so that I could subtly introduce them to become users of my blog. However, as time went on, I increasingly felt "exhausted" because the Threads algorithm became less and less aligned with my direction. In other words, the content created was not popular.

    For example, my posts often lean towards sharing information, news, or personal experiences drawn from learning or doing something. It seems that such posts are not highly regarded and often get buried after just over... 100 views. Hmm... Could the problem be me? Knowing this, why not change the content to be more suitable for the platform?

    I have observed Threads, and the content that spreads the most easily often contains controversial elements or a prejudice about something, sometimes it’s simply stating something "naively" that they know will definitely get interactions. However, I almost do not like directing users towards this kind of content. People might call me stubborn, and I accept that. Everyone has different content directions and audiences; the choice is theirs.

    So, from then on, I mainly write here. Only occasionally, if I find something very interesting, do I go on Threads to "show off." Here, people still come to read daily; no matter who you are, I am sure that you can recognize the message I want to convey through each post. At the very least, we share a common direction regarding content. Sometimes, the scariest thing is not that no one reads what you write, but that they read it and then forget it in an instant. Quantity is important, but quality is what brings us closer together.

    Thank you all 🤓

    » Read more
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » 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...