PyCasbin

2.8.0 · active · verified Sat Apr 11

PyCasbin is a powerful and efficient open-source authorization library for Python projects (currently v2.8.0). It supports enforcing access control based on various models like ACL, RBAC, and ABAC. The library is actively maintained with frequent updates and aims for feature parity across its different language implementations.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `casbin.Enforcer` with a model (`.conf`) and policy (`.csv`) file, and then use the `enforce()` method to check permissions. It also shows a dynamic policy addition. Note the use of `asyncio.run` as the `enforce` method is asynchronous.

import casbin
import os

# Create dummy model and policy files for the example
with open('model.conf', 'w') as f:
    f.write('''
[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
''')

with open('policy.csv', 'w') as f:
    f.write('''
p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, *
''')

async def run_enforcer():
    # Initialize an enforcer with a model file and a policy file
    # For real applications, use an adapter (e.g., casbin_sqlalchemy_adapter)
    e = casbin.Enforcer('model.conf', 'policy.csv')

    # Test if 'alice' can 'read' 'data1'
    if await e.enforce('alice', 'data1', 'read'):
        print("Alice CAN read data1")
    else:
        print("Alice CANNOT read data1")

    # Test if 'bob' can 'read' 'data2'
    if await e.enforce('bob', 'data2', 'read'):
        print("Bob CAN read data2")
    else:
        print("Bob CANNOT read data2")

    # Test if 'bob' can 'write' 'data2'
    if await e.enforce('bob', 'data2', 'write'):
        print("Bob CAN write data2")
    else:
        print("Bob CANNOT write data2")

    # Add a policy dynamically
    await e.add_policy('cathy', 'data3', 'read')
    if await e.enforce('cathy', 'data3', 'read'):
        print("Cathy CAN read data3 (after adding policy)")

    # Remove temporary files
    os.remove('model.conf')
    os.remove('policy.csv')

if __name__ == '__main__':
    import asyncio
    asyncio.run(run_enforcer())

view raw JSON →