Introduction to Casbin for Role-Based Access Control (RBAC)
Casbin is an open-source, highly efficient library for managing access control models, especially role-based access control (RBAC), in your applications. With Casbin, you can enforce policies for models such as ACL, RBAC, ABAC, and others. Let’s explore its APIs and how to integrate them into your application.
Basic Usage
First, install Casbin via npm:
npm install casbin
Initialize a Casbin Enforcer
The enforcer handles policy enforcement:
const { newEnforcer } = require('casbin');
async function initEnforcer() {
const enforcer = await newEnforcer('path/to/model.conf', 'path/to/policy.csv');
return enforcer;
}
Adding Policies
Add a policy rule:
async function addPolicy(enforcer) {
await enforcer.addPolicy('alice', 'data1', 'read');
}
Removing Policies
Remove a policy rule:
async function removePolicy(enforcer) {
await enforcer.removePolicy('alice', 'data1', 'read');
}
Enforcing Policies
Check if a policy permits a user’s action:
async function enforcePolicy(enforcer) {
const result = await enforcer.enforce('alice', 'data1', 'read');
console.log(result); // true or false
}
Managing Roles
Add and remove roles for users:
async function manageRoles(enforcer) {
await enforcer.addRoleForUser('alice', 'admin');
await enforcer.deleteRoleForUser('alice', 'admin');
}
Example Application
Below is a simple example showing how to integrate Casbin into an Express application:
const express = require('express'); const { newEnforcer } = require('casbin');
(async () => {
const enforcer = await newEnforcer('path/to/model.conf', 'path/to/policy.csv');
const app = express();
app.use(async (req, res, next) => {
const { user } = req; // Assume user information is available in req.user
const isAllowed = await enforcer.enforce(user.name, req.path, req.method);
if (isAllowed) {
next();
} else {
res.status(403).send('Forbidden');
}
});
app.get('/data1', (req, res) => {
res.send('Data1 access granted');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
})();
With this setup, you can manage permissions and access to routes using Casbin policies.
Hash: b14a6bb205e7b7ac7ea0b175cce38d60498112a51b4995046194dea144b8ab07