Home >Web Front-end >JS Tutorial >Learn about Node.js Casbin
【Video tutorial recommendation: nodejs tutorial】
Casbin is a powerful and efficient open source access control framework whose permission management mechanism supports multiple access control models.
Casbin can:
Casbin cannot:
casbin.org/docs/en/overview
# NPMnpm install casbin --save# Yarnyarn add casbin
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.
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:
# 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!