node-casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser
Top Related Projects
Open Source, Google Zanzibar-inspired permissions database to enable fine-grained authorization for customer applications
Open Source (Go) implementation of "Zanzibar: Google's Consistent, Global Authorization System". Ships gRPC, REST APIs, newSQL, and an easy and granular permission language. Supports ACL, RBAC, and other access models.
Open Policy Agent (OPA) is an open source, general-purpose policy engine.
Open Source Identity and Access Management For Modern Applications and Services
Quick Overview
Node-Casbin is a powerful and efficient open-source access control library for Node.js. It provides support for enforcing authorization based on various access control models, including ACL, RBAC, ABAC, and more. Node-Casbin offers a flexible policy language and can be easily integrated into existing Node.js applications.
Pros
- Supports multiple access control models out of the box
- Highly flexible and customizable policy language
- Efficient policy enforcement with minimal performance overhead
- Easy integration with various backends (e.g., file, database)
Cons
- Learning curve for understanding and implementing complex policies
- Limited built-in support for dynamic policy updates
- Documentation could be more comprehensive for advanced use cases
Code Examples
- Basic usage with file-based policy:
const { newEnforcer } = require('casbin');
async function checkPermission() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const result = await enforcer.enforce('alice', 'data1', 'read');
console.log(result ? 'Allowed' : 'Denied');
}
checkPermission();
- Adding a policy dynamically:
const { newEnforcer } = require('casbin');
async function addPolicy() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const added = await enforcer.addPolicy('bob', 'data2', 'write');
console.log(added ? 'Policy added' : 'Policy already exists');
}
addPolicy();
- Checking permissions for a user with roles:
const { newEnforcer } = require('casbin');
async function checkRolePermission() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const result = await enforcer.enforce('alice', 'data1', 'read');
const roles = await enforcer.getRolesForUser('alice');
console.log(`Allowed: ${result}, Roles: ${roles.join(', ')}`);
}
checkRolePermission();
Getting Started
To use Node-Casbin in your project:
-
Install the package:
npm install casbin
-
Create a model file (e.g.,
model.conf
) and a policy file (e.g.,policy.csv
). -
Use the library in your code:
const { newEnforcer } = require('casbin');
async function main() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const result = await enforcer.enforce('alice', 'data1', 'read');
console.log(result ? 'Allowed' : 'Denied');
}
main();
For more advanced usage and configuration options, refer to the official Node-Casbin documentation.
Competitor Comparisons
Open Source, Google Zanzibar-inspired permissions database to enable fine-grained authorization for customer applications
Pros of SpiceDB
- Built with performance and scalability in mind, suitable for large-scale applications
- Provides a unified API for multiple storage backends (PostgreSQL, MySQL, etc.)
- Supports real-time updates and subscriptions for permission changes
Cons of SpiceDB
- Steeper learning curve due to its more complex architecture
- Requires additional infrastructure setup compared to Node-Casbin
- Less flexible in terms of policy definition formats
Code Comparison
Node-Casbin:
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const allowed = await enforcer.enforce('alice', 'data1', 'read');
SpiceDB:
client := zed.NewClient(zed.WithAddr("localhost:50051"))
allowed, err := client.CheckPermission(ctx, &v1.CheckPermissionRequest{
Resource: &v1.ObjectReference{ObjectType: "document", ObjectId: "1"},
Permission: "view",
Subject: &v1.SubjectReference{Object: &v1.ObjectReference{ObjectType: "user", ObjectId: "alice"}},
})
Node-Casbin offers a simpler API and configuration, while SpiceDB provides more advanced features for complex authorization scenarios. Node-Casbin is easier to integrate into existing Node.js applications, whereas SpiceDB is designed as a standalone service with language-agnostic clients.
Open Source (Go) implementation of "Zanzibar: Google's Consistent, Global Authorization System". Ships gRPC, REST APIs, newSQL, and an easy and granular permission language. Supports ACL, RBAC, and other access models.
Pros of Keto
- More comprehensive access control system with built-in identity management
- Supports fine-grained permissions and relationship-based access control
- Offers a RESTful API for easy integration with various applications
Cons of Keto
- Steeper learning curve due to its more complex architecture
- Requires additional setup and infrastructure compared to Node-Casbin
- May be overkill for simpler authorization scenarios
Code Comparison
Keto (using Go):
import "github.com/ory/keto/proto/ory/keto/acl/v1alpha1"
// Check if a user has access to a resource
allowed, err := c.Check(ctx, &acl.CheckRequest{
Namespace: "files",
Object: "file:1",
Relation: "view",
Subject: "user:john",
})
Node-Casbin (using JavaScript):
const enforcer = await casbin.newEnforcer('model.conf', 'policy.csv');
// Check if a user has access to a resource
const allowed = await enforcer.enforce('john', 'file1', 'view');
Both Keto and Node-Casbin are powerful authorization libraries, but they cater to different use cases. Keto is more suitable for complex, large-scale applications requiring fine-grained access control, while Node-Casbin offers a simpler, more lightweight solution for basic authorization needs in Node.js environments.
Open Policy Agent (OPA) is an open source, general-purpose policy engine.
Pros of OPA
- More versatile policy language (Rego) for complex decision-making
- Broader ecosystem with integrations for various platforms and tools
- Supports distributed policy enforcement across microservices
Cons of OPA
- Steeper learning curve due to Rego language complexity
- Potentially higher resource usage for complex policies
- Less focused on specific access control models (e.g., RBAC, ABAC)
Code Comparison
Node-Casbin example:
const enforcer = await newEnforcer('model.conf', 'policy.csv');
const allowed = await enforcer.enforce('alice', 'data1', 'read');
OPA example:
package httpapi.authz
default allow = false
allow {
input.method == "GET"
input.path == ["users", user_id]
input.user_id == user_id
}
Node-Casbin focuses on straightforward policy enforcement using a simple API, while OPA uses a more expressive policy language (Rego) for complex decision-making. Node-Casbin is tailored for Node.js applications, whereas OPA is language-agnostic and can be integrated into various environments. Both projects aim to solve authorization problems, but OPA offers a more flexible and powerful approach at the cost of increased complexity.
Open Source Identity and Access Management For Modern Applications and Services
Pros of Keycloak
- Comprehensive identity and access management solution with built-in user management, authentication, and authorization features
- Supports various protocols like OAuth 2.0, OpenID Connect, and SAML 2.0 out of the box
- Offers a user-friendly admin console for easy configuration and management
Cons of Keycloak
- More complex setup and configuration compared to Node-Casbin's lightweight approach
- Requires additional infrastructure and resources to run as a separate service
- May be overkill for projects that only need basic access control functionality
Code Comparison
Node-Casbin:
const enforcer = await casbin.newEnforcer('model.conf', 'policy.csv');
const allowed = await enforcer.enforce('alice', 'data1', 'read');
Keycloak:
const keycloak = new Keycloak({ /* config */ });
app.use(keycloak.middleware());
app.get('/protected', keycloak.protect(), (req, res) => {
// Protected route
});
Node-Casbin focuses on policy enforcement, while Keycloak provides a more comprehensive authentication and authorization solution. Node-Casbin is lightweight and flexible, making it suitable for projects that need customizable access control. Keycloak offers a full-featured IAM system but requires more setup and resources.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Node-Casbin
Sponsored by
Build auth with fraud prevention, faster.
Try Stytch for API-first authentication, user & org management, multi-tenant SSO, MFA, device fingerprinting, and more.
News: still worry about how to write the correct node-casbin
policy? Casbin online editor is coming to help!
node-casbin
is a powerful and efficient open-source access control library for Node.JS projects. It provides support for enforcing authorization based on various access control models.
All the languages supported by Casbin:
Casbin | jCasbin | node-Casbin | PHP-Casbin |
production-ready | production-ready | production-ready | production-ready |
PyCasbin | Casbin.NET | Casbin-CPP | Casbin-RS |
production-ready | production-ready | beta-test | production-ready |
Documentation
https://casbin.org/docs/overview
Installation
# NPM
npm install casbin --save
# Yarn
yarn add casbin
Get started
New a node-casbin
enforcer with a model file and a policy file, see Model section for details:
// For Node.js:
const { newEnforcer } = require('casbin');
// For browser:
// import { newEnforcer } from 'casbin';
const enforcer = await newEnforcer('basic_model.conf', 'basic_policy.csv');
Note: you can also initialize an enforcer with policy in DB instead of file, see Persistence section for details.
Add an enforcement hook into your code right before the access happens:
const sub = 'alice'; // the user that wants to access a resource.
const obj = 'data1'; // the resource that is going to be accessed.
const act = 'read'; // the operation that the user performs on the resource.
// Async:
const res = await enforcer.enforce(sub, obj, act);
// Sync:
// const res = enforcer.enforceSync(sub, obj, act);
if (res) {
// permit alice to read data1
} else {
// deny the request, show an error
}
Besides the static policy file, node-casbin
also provides API for permission management at run-time.
For example, You can get all the roles assigned to a user as below:
const roles = await enforcer.getRolesForUser('alice');
See Policy management APIs for more usage.
Policy management
Casbin provides two sets of APIs to manage permissions:
- Management API: the primitive API that provides full support for Casbin policy management.
- RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code.
Official Model
https://casbin.org/docs/supported-models
Policy persistence
https://casbin.org/docs/adapters
Policy consistence between multiple nodes
https://casbin.org/docs/watchers
Role manager
https://casbin.org/docs/role-managers
Contributors
This project exists thanks to all the people who contribute.
Backers
Thank you to all our backers! ð [Become a backer]
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
License
This project is licensed under the Apache 2.0 license.
Contact
If you have any issues or feature requests, please contact us. PR is welcomed.
- https://github.com/casbin/node-casbin/issues
- hsluoyz@gmail.com
- Tencent QQ group: 546057381
Top Related Projects
Open Source, Google Zanzibar-inspired permissions database to enable fine-grained authorization for customer applications
Open Source (Go) implementation of "Zanzibar: Google's Consistent, Global Authorization System". Ships gRPC, REST APIs, newSQL, and an easy and granular permission language. Supports ACL, RBAC, and other access models.
Open Policy Agent (OPA) is an open source, general-purpose policy engine.
Open Source Identity and Access Management For Modern Applications and Services
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot