Casbin

1.43.0 · active · verified Sat Apr 11

Casbin is a powerful and efficient open-source access control library for Python projects. It provides support for enforcing authorization based on various access control models like ACL, RBAC, and ABAC. Authorization models are defined using `.conf` files, and policies are stored in `.csv` files or various database backends via adapters. The library is actively maintained with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Casbin Enforcer with a basic model and policy, and then use it to check authorization requests. It creates temporary `model.conf` and `policy.csv` files, which define the access control structure and rules respectively. The `enforce` method is then called to determine if a subject (user), object (resource), and action combination is allowed.

import casbin
import os

# Create a simple model.conf file
model_conf_content = """
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

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

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
"""

# Create a simple policy.csv file
policy_csv_content = """
p, alice, data1, read
p, bob, data2, write
"""

# Save model and policy to temporary files
with open("model.conf", "w") as f:
    f.write(model_conf_content)
with open("policy.csv", "w") as f:
    f.write(policy_csv_content)

try:
    # Initialize the enforcer
    e = casbin.Enforcer("model.conf", "policy.csv")

    # Test enforcement
    print(f"Alice can read data1: {e.enforce('alice', 'data1', 'read')}") # True
    print(f"Alice can write data1: {e.enforce('alice', 'data1', 'write')}") # False
    print(f"Bob can read data2: {e.enforce('bob', 'data2', 'read')}") # False
    print(f"Bob can write data2: {e.enforce('bob', 'data2', 'write')}") # True
    print(f"Charlie can read data1: {e.enforce('charlie', 'data1', 'read')}") # False
finally:
    # Clean up temporary files
    os.remove("model.conf")
    os.remove("policy.csv")

view raw JSON →