search
HomeWeb Front-endJS TutorialLearn about Node.js Casbin

Learn about Node.js Casbin

Aug 19, 2020 am 10:16 AM
node.js

Learn about Node.js Casbin

【Video tutorial recommendation: nodejs tutorial

Overview

Casbin is a powerful and efficient open source access control framework whose permission management mechanism supports multiple access control models.

What is Casbin?

Casbin can:

  • Supports custom request format, the default request format is {subject, object, action}.
  • It has two core concepts: access control model model and policy policy.
  • Supports multi-level role inheritance in RBAC. Not only subjects can have roles, but resources can also have roles.
  • Supports super users, such as root or Administrator, who can access any resources without being restricted by authorization policies.
  • Supports a variety of built-in operators, such as keyMatch, to facilitate management of path-based resources, such as /foo/bar can be mapped to /foo*

Casbin cannot:

  • Identity authentication (that is, verifying the user's user name and password), casbin is only responsible for access control. There should be other specialized components responsible for identity authentication, and then casbin should perform access control. The two work together.
  • Manage user list or role list. Casbin believes that it is more appropriate for the project itself to manage the user and role lists. Users usually have their passwords, but Casbin is not designed to be a container for storing passwords. Instead, it stores the mapping relationship between users and roles in the RBAC scheme.

Documentation

casbin.org/docs/en/overview

Installation

# NPMnpm install casbin --save# Yarnyarn add casbin

Let’s get started

Creating Casbin enforcer requires a model file and policy file as parameters:

import { newEnforcer } from 'casbin';const enforcer = await newEnforcer('basic_model.conf', 'basic_policy.csv');

You can also initialize the enforcer with the policy in the DB instead of the file, see Adapter for details.

const sub = 'alice'; // 想要访问资源的用户。const obj = 'data1'; // 将要访问的资源。const act = 'read'; // 用户对资源执行的操作。const res = await enforcer.enforce(sub, obj, act);if (res) {
  // 允许 alice 读取数据1} else {
  // 拒绝请求,显示错误}

In addition to static policy files, node-casbin also provides an API for permission management at runtime, for example, you can obtain all roles assigned to a user as follows:

const roles = await enforcer.getRolesForUser('alice');

Please refer to Management API and RBAC API for more usage methods.

Working Principle

In Casbin, the access control model is abstracted into a file based on PERM (Policy, Effect, Request, Matcher) . Therefore, switching or upgrading a project's authorization mechanism is as simple as modifying the configuration. You can customize your own access control model by combining the available models. For example, you can have RBAC roles and ABAC attributes in one model and share a set of policy rules.

The most basic and simple model in Casbin is ACL. The model CONF in ACL is:

# 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

The example policy of ACL model is as follows:

p, alice, data1, read
p, bob, data2, write

This means:

  • alice can read data1
  • bob can write data2
    For too long single-line configuration, you can also break the line by adding '' at the end:
# Matchers[matchers]m = r.sub == p.sub && r.obj == p.obj \ 
  && r.act == p.act

In addition, for ABAC, you can use Casbin golang version Try the following (not yet supported by jCasbin and Node-Casbin) operation:

# Matchers[matchers]m = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3')

But you should ensure that the length of the array is greater than 1, otherwise it will cause panic.

For more operations, you can check out govaluate.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Learn about Node.js Casbin. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
JavaScript Object Models: Deep Copying, Shallow Copying, and Considerations for Java SerializationJavaScript Object Models: Deep Copying, Shallow Copying, and Considerations for Java SerializationJul 23, 2025 am 04:07 AM

Shallow copy only copies the top-level properties of the object, nested reference types share the same memory address, and modifying the copy will affect the original object; deep copy recursively copies all levels to ensure complete independence. For example, using Object.assign or extension operators is a shallow copy, modifying nested objects will reflect the original object; while JSON.parse(JSON.stringify(obj)) or Lodash's _.cloneDeep() can achieve deep copy to avoid mutual influence. In addition, deep copying requires attention to special types of processing such as functions, circular references, and Date. When communicating across languages, the impact of Java serialization on data structures must also be considered.

How to select an HTML element by class or tag name in JS?How to select an HTML element by class or tag name in JS?Jul 23, 2025 am 04:01 AM

Selecting HTML elements in JavaScript can be achieved in three ways: 1. Use getElementsByClassName to select by class name, return dynamic HTMLCollection, you need to write the class name, such as 'box', and access the first element through boxes[0]; 2. Use getElementsByTagName to select by tag name, and also return dynamic HTMLCollection, suitable for batch operations such as modifying all li styles; 3. Use querySelectorAll to select by CSS selector, support more complex selection logic, return static NodeList, if only the first match is required, you can use querySe

Working with Dates in JavaScript: A Complete GuideWorking with Dates in JavaScript: A Complete GuideJul 23, 2025 am 03:59 AM

JavaScript's date processing requires attention to creating, getting set values, formatting and time zone issues. 1. Create a Date object by using no parameters, timestamps, date strings or components; note that the month starts at 0 and the browser parses the strings may be inconsistent. 2. Use getDate, setDate and other methods to get/set the value, and use getTime() to compare the date. 3. Intl.DateTimeFormat can be used to ensure consistency, and third-party libraries can also be used. 4. UTC method should be used to deal with time zones to avoid confusion. The sending server recommends using UTC and converting it to the backend.

JavaScript Performance Optimization: Debouncing and ThrottlingJavaScript Performance Optimization: Debouncing and ThrottlingJul 23, 2025 am 03:57 AM

Debouncingdelaysfunctionexecutionuntilafterapauseinactivity,idealforsearchinputsandformvalidation;2.Throttlinglimitsexecutiontoonceperfixedinterval,perfectforscrollandmousemoveevents;bothreduceperformanceloadwhilepreservingUX.

Leveraging JavaScript Proxies and Reflect API for Advanced Metaprogramming with Java InteropLeveraging JavaScript Proxies and Reflect API for Advanced Metaprogramming with Java InteropJul 23, 2025 am 03:55 AM

JavaScriptProxies and ReflectAPI can be used to enhance the interoperability of Java and JavaScript in Nashorn or GraalVM environments. 1. Use Proxy to intercept access to Java objects, such as recording attribute access logs or dynamically modifying the return value, and implementing it through get traps and Reflect.get; 2. You can proxie the Java class itself and control constructor calls through construct traps; 3. Use apply traps to automatically convert parameter types before calling Java methods to improve compatibility between JS and Java; 4. Reflect provides more consistent operation methods, such as Reflect.has

Implementing JavaScript Security Headers in Node.jsImplementing JavaScript Security Headers in Node.jsJul 23, 2025 am 03:48 AM

The method of setting up JavaScript security headers in Node.js applications is to use Helmet middleware to implement it through the backend. 1. Install and introduce the Helmet package and add it to the Express middleware chain to enable the default security headers; 2. Common security headers include CSP to prevent XSS attacks, X-Content-Type-Options to avoid MIME type guessing, X-Frame-Options to prevent click hijacking, HSTS to force HTTPS access, etc.; 3. CSP policies can be customized to meet external resource loading needs, but 'unsafe-inline' should be avoided, and Nonce or Hash is recommended instead; 4. Enable

Advanced JavaScript Readable and Writable StreamsAdvanced JavaScript Readable and Writable StreamsJul 23, 2025 am 03:47 AM

Readable and writable streams in JavaScript achieve efficient data transmission through chunking processing. 1. ReadableStream is used to read data in asynchronously in blocks, suitable for large file reading, HTTP response and other scenarios; 2. WritableStream receives data and processes it, such as writing to files or recording logs; 3. Use the .pipe() method to automatically process back pressure, connecting readable and writable streams; 4. Transform stream can be converted during data flow; 5. In actual use, pay attention to error processing, back pressure control and correct ending of streams. Mastering these key points will help improve big data processing capabilities and performance.

How does hoisting work in JavaScript?How does hoisting work in JavaScript?Jul 23, 2025 am 03:45 AM

Variable and function enhancement is the mechanism by which the JavaScript engine collects declarations into memory during the compilation phase, and does not really move the code. When a variable is declared using var, it will be promoted to the top of the scope, but the assignment remains in place; let and const will also be promoted, but will not be initialized, and it will enter a "temporary dead zone", and an error will be reported when access is reported. Function declarations will be fully promoted, including the function body, so they can be called before declaration; while the function expression only has the variable name promoted, and the function body is still in place. In actual development, suggestions are: 1. Declare variables at the top of the scope; 2. Priority is given to let and const; 3. Avoid calling function expressions or arrow functions before the function; 4. Do not repetitively declare functions and variables with the same name. Understanding the lifting mechanism helps

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools