Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHESPTRUFRDEEN

Elysia Tools

Navigation

Authentication & Authorization

Casbin Access Control Library

Powerful and efficient open-source access control library

Samples

Entries inside this sample collection

CodejavascriptSimple

Casbin RBAC Basic Setup

Role-Based Access Control with Casbin

Difficulty

3/10

Estimated time

10 min

Tags

casbin, rbac, authorization, security

Prerequisites

Node.js, Basic authorization concepts

javascript
// Casbin RBAC Setup
const { newEnforcer, newModelFromString, StringAdapter } = 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 = `
p, admin, data1, read
p, bob, data2, write
g, alice, admin
`;

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

async function main() {
  const modelConf = newModelFromString(model);
  const policyAdapter = new StringAdapter(policy);
  const enforcer = await newEnforcer(modelConf, policyAdapter);

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

main().catch(console.error);
CodejavascriptIntermediate

Casbin Express.js Middleware

Authorization middleware for Express.js

Difficulty

5/10

Estimated time

15 min

Tags

casbin, express, middleware, api

Prerequisites

Node.js, Express.js, Casbin basics

javascript
// 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();
CodejavascriptComplex

Casbin ABAC with Attributes

Attribute-Based Access Control with dynamic rules

Difficulty

7/10

Estimated time

20 min

Tags

casbin, abac, attributes, advanced

Prerequisites

Casbin basics, ABAC concepts

javascript
// 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
CodejavascriptIntermediate

Casbin Database Adapter

Store policies in database with persistent storage

Difficulty

6/10

Estimated time

15 min

Tags

casbin, database, persistence, mongodb

Prerequisites

Node.js, Database basics, Casbin

javascript
// Casbin Database Adapter
const express = require('express');
const { newEnforcer } = require('casbin');
const { MongooseAdapter } = require('casbin-mongoose-adapter');

const app = express();
app.use(express.json());

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

  // Create enforcer with database adapter
  const enforcer = await 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();

Tools

Tools frequently paired with this sample

Related

Related sample collections

Tool usage guide

Sample-focused context for search and workflow understanding

Title

Casbin Access Control Library

Description

Powerful and efficient open-source access control library

Overview

Powerful and efficient open-source access control library

When to use

  • Use this sample set when you want reference inputs for Casbin Access Control Library.
  • Use it to preview output formats and compare related sample variants.

How it works

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

Use cases

  • Casbin RBAC Basic Setup
  • Casbin Express.js Middleware
  • Casbin ABAC with Attributes
  • Casbin Database Adapter

FAQ

What is included in Casbin Access Control Library?

This page includes curated sample entries, related tools, and neighboring sample collections for Casbin Access Control Library.

Home
Tools3197
Samples593
Visualizations461
Viewers103
Hubs229
Tags333
Images, Audio & Video655

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance644

Calculators, numerics, date logic, statistics, and finance tools

Design & Color296

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

UI Screenshot Structure Review and Development Handoff
Piano Sketch Creation, MIDI Review and Listening Demo Handoff
Retro Game Texture Review and Asset Handoff
Screenshot-Based Procedure Guide Review and Handoff
Responsive Page Change Review and Evidence Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Media

Audio Breath Control Editor

Detect breaths in speech and naturally crossfade to reduce, remove, or keep them.

Media

Duplicate Audio Library Finder

Find exact and near-duplicate audio across uploaded files or a ZIP, including copies saved with different codecs.

Development

HTTP Cache-Control CDN Edge TTL Budget Optimizer

Analyze Cache-Control directives, calculate browser/shared-cache TTL and stale budgets, detect directive conflicts, and compare static behavior notes for generic HTTP, Fastly, Cloudflare, and Akamai.

Data Processing

Log Parser - Apache/Nginx Access Log Parser

Parse Apache/Nginx access logs using regex patterns and extract structured data

Authentication & Authorization

OAuth 2.0 & OpenID Connect Samples

OAuth 2.0 authorization framework and OpenID Connect authentication protocol examples

Authentication & Authorization

OAuth 2.0 Samples

OAuth 2.0 implementation examples including authorization flows, client configurations, and security best practices

Security

JWT Samples

Comprehensive JWT examples from basic token structure to advanced security implementations

Security

Zero Trust Architecture Samples

Comprehensive Zero Trust architecture samples covering identity authentication, network segmentation, micro-segmentation strategies, and secure access control

Authentication & Authorization

Passport.js Authentication Middleware

Node.js authentication middleware with Passport.js and various strategies

Authentication & Authorization

SAML Samples

SAML (Security Assertion Markup Language) implementation examples including SSO, metadata, and identity provider configurations