Using Casbin for user authorization in a system

Using Casbin for user authorization in a system

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

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