Casbin Access Control Library

Powerful and efficient open-source access control library

💻 Casbin RBAC Basic Setup javascript

🟢 simple ⭐⭐

Role-Based Access Control with Casbin

⏱️ 10 min 🏷️ casbin, rbac, authorization, security
Prerequisites: Node.js, Basic authorization concepts
// Casbin RBAC Setup
const { Enforcer } = require('casbin');

const model = `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`;

const policy = [
  ['alice', 'data1', 'read'],
  ['bob', 'data2', 'write'],
  ['alice', 'admin', 'data1']
];

const enforcer = new Enforcer(model, policy);

// Add role for user
enforcer.addRoleForUser('alice', 'admin');

// Check permission
async function checkPermission(user, resource, action) {
  const allowed = await enforcer.enforce(user, resource, action);
  console.log(`${user} can ${action} ${resource}: ${allowed}`);
  return allowed;
}

checkPermission('alice', 'data1', 'read'); // true
checkPermission('bob', 'data2', 'write');   // true

💻 Casbin Express.js Middleware javascript

🟡 intermediate ⭐⭐⭐

Authorization middleware for Express.js

⏱️ 15 min 🏷️ casbin, express, middleware, api
Prerequisites: Node.js, Express.js, Casbin basics
// Casbin Express Middleware
const express = require('express');
const { newEnforcer } = require('casbin');

async function createAuthMiddleware(modelPath, policyPath) {
  const enforcer = await newEnforcer(modelPath, policyPath);

  return async (req, res, next) => {
    const user = req.user?.id || 'anonymous';
    const resource = req.path;
    const action = req.method.toLowerCase();

    const allowed = await enforcer.enforce(user, resource, action);

    if (!allowed) {
      return res.status(403).json({ error: 'Access denied' });
    }

    next();
  };
}

// Usage
const app = express();

// Initialize middleware
async function initApp() {
  const authMiddleware = await createAuthMiddleware(
    'path/to/model.conf',
    'path/to/policy.csv'
  );

  // Apply to routes
  app.get('/admin', authMiddleware, (req, res) => {
    res.json({ message: 'Admin area' });
  });

  app.post('/users', authMiddleware, (req, res) => {
    res.json({ message: 'User created' });
  });
}

initApp();

💻 Casbin Database Adapter javascript

🟡 intermediate ⭐⭐⭐

Store policies in database with persistent storage

⏱️ 15 min 🏷️ casbin, database, persistence, mongodb
Prerequisites: Node.js, Database basics, Casbin
// Casbin Database Adapter
const { Enforcer } = require('casbin');
const { MongooseAdapter } = require('casbin-mongoose-adapter');

async function setupCasbinWithDB() {
  // Initialize database adapter
  const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27017/casbin');

  // Create enforcer with database adapter
  const enforcer = await Enforcer.newEnforcer(
    'path/to/model.conf',
    adapter
  );

  // Add policies to database
  await enforcer.addPolicy('alice', 'data1', 'read');
  await enforcer.addPolicy('bob', 'data2', 'write');

  // Add roles
  await enforcer.addRoleForUser('charlie', 'admin');

  // Check permission
  const allowed = await enforcer.enforce('alice', 'data1', 'read');

  // Get all policies
  const policies = await enforcer.getPolicy();
  console.log('All policies:', policies);

  // Remove policy
  await enforcer.removePolicy('alice', 'data1', 'read');

  return enforcer;
}

// Usage example
async function initAuthSystem() {
  const enforcer = await setupCasbinWithDB();

  // Dynamic policy management
  app.post('/policies', async (req, res) => {
    const { sub, obj, act } = req.body;
    await enforcer.addPolicy(sub, obj, act);
    res.json({ message: 'Policy added' });
  });
}

initAuthSystem();

💻 Casbin ABAC with Attributes javascript

🔴 complex ⭐⭐⭐⭐

Attribute-Based Access Control with dynamic rules

⏱️ 20 min 🏷️ casbin, abac, attributes, advanced
Prerequisites: Casbin basics, ABAC concepts
// Casbin ABAC with Attributes
const model = `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub_rule, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = eval(p.sub_rule) && r.obj == p.obj && r.act == p.act
`;

// Policy with attribute rules
const policies = [
  ['r.obj.Owner == r.sub', 'document', 'write'],
  ['r.sub.Role == "admin"', 'document', 'delete'],
  ['r.obj.Department == r.sub.Department', 'report', 'read']
];

// Context function for ABAC
function createContext(user, resource) {
  return {
    sub: {
      ...user,
      Role: user.role,
      Department: user.department
    },
    obj: {
      ...resource,
      Owner: resource.owner,
      Department: resource.department
    }
  };
}

// Check with attributes
async function checkABAC(enforcer, user, resource, action) {
  const ctx = createContext(user, resource);
  const allowed = await enforcer.enforce(
    ctx.sub,
    ctx.obj,
    action
  );
  return allowed;
}

const user = { id: 'alice', role: 'manager', department: 'finance' };
const doc = { id: 'doc1', owner: 'alice', department: 'finance' };

checkABAC(enforcer, user, doc, 'write'); // true