Casbin
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
- breaking When upgrading to PyCasbin v2 (which was released with version 0.20.0), custom effectors require a rewrite due to API changes.
- gotcha The core `casbin` library only includes a default file adapter. For policy persistence in databases (e.g., MySQL, PostgreSQL, MongoDB), you must install a separate, corresponding adapter library.
- gotcha Casbin handles *authorization* (who can do what on which resource) but explicitly *does not* handle authentication (verifying user identity/passwords).
- gotcha In distributed systems, the `SyncEnforcer`'s periodic policy reloading might lead to temporary inconsistencies or frequent database hits. Consider using filtered policy loading or a robust caching strategy.
Install
-
pip install casbin
Imports
- Enforcer
from casbin import Enforcer
Quickstart
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")