Using Casbin for user authorization in a system

Using Casbin for user authorization in a system

Daily short news for you
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more
  • CloudFlare has introduced the pay per crawl feature to charge for each time AI "crawls" data from your website. What does that mean 🤔?

    The purpose of SEO is to help search engines see the website. When users search for relevant content, your website appears in the search results. This is almost a win-win situation where Google helps more people discover your site, and in return, Google gets more users.

    Now, the game with AI Agents is different. AI Agents have to actively seek out information sources and conveniently "crawl" your data, then mix it up or do something with it that we can't even know. So this is almost a game that benefits only one side 🤔!?

    CloudFlare's move is to make AI Agents pay for each time they retrieve data from your website. If they don’t pay, then I won’t let them read my data. Something like that. Let’s wait a bit longer and see 🤓.

    » Read more
  • Continuing to update on the lawsuit between the Deno group and Oracle over the name JavaScript: It seems that Deno is at a disadvantage as the court has dismissed the Deno group's complaint. However, in August, they (Oracle) must be held accountable for each reason, acknowledging or denying the allegations presented by the Deno group in the lawsuit.

    JavaScript™ Trademark Update

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...