PyCasbin Documentation

repository·master·Indexed 23 days ago

https://github.com/apache/casbin-pycasbin

An open-source access control library for Python that separates authorization logic from permission data. PyCasbin supports various models including ACL, RBAC, ABAC, and RESTful patterns using the PERM metamodel. It provides an Enforcer for standard permission checks and an AsyncEnforcer for I/O-heavy applications using async/await.

Tokens
2K
Snippets
4
Records
8
Agent score
33%

What's inside PyCasbin

  1. Supported access control models

    master

    PyCasbin supports a wide variety of access control models, including:

    • ACL (Access Control List): Basic permission sets.
    • RBAC (Role-Based Access Control): Permissions assigned to roles, which are then assigned to users.
    • RBAC with domains/tenants: Users have different roles depending on the domain/tenant.
    • ABAC (Attribute-Based Access Control): Uses attributes of the subject, object, or environment (e.g., resource.Owner).
    • RESTful: Supports path patterns (e.g., /res/*, /res/:id) and HTTP methods.
    • Deny-override: A model where a 'deny' rule overrides an 'allow' rule.
    • Priority: Rules can be prioritized similarly to firewall rules.
  2. How Casbin access control models work

    master

    Casbin abstracts access control models into a configuration file (CONF) based on the PERM metamodel:

    1. Request definition (r): Defines the structure of the request (e.g., sub, obj, act).
    2. Policy definition (p): Defines the structure of the policy rules.
    3. Policy effect (e): Defines how the results of the matchers are combined (e.g., some(where (p.eft == allow)) means if any policy allows, the request is allowed).
    4. Matchers (m): Defines the logic used to match the request against the policies.

    By modifying the CONF file, you can switch between different models like ACL, RBAC, or ABAC without changing your application code.

    # Request definition
    [request_definition]
    r = sub, obj, act
    
    # Policy definition
    [policy_definition]
    p = sub, obj, act
    
    # Policy effect
    [policy_effect]
    e = some(where (p.eft == allow))
    
    # Matchers
    [matchers]
    m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
  3. Use AsyncEnforcer for I/O-heavy applications

    master

    If your application uses async/await and relies heavily on I/O operations, use casbin.AsyncEnforcer.

    To use it:

    1. Initialize an async engine and an async adapter (a subclass of AsyncAdapter).
    2. Create the AsyncEnforcer instance by passing the model file path and the async adapter.
    3. Call await e.load_policy() to load the policies from the adapter.
    4. Use await e.enforce(...) to check permissions.

    Built-in async adapters are available in casbin.persist.adapters.asyncio.

    import asyncio
    import casbin
    from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
    from sqlalchemy.orm import sessionmaker
    from casbin_async_sqlalchemy_adapter import Adapter, CasbinRule
    
    async def get_enforcer():
        engine = create_async_engine("sqlite+aiosqlite://", future=True)
        adapter = Adapter(engine)
        await adapter.create_table()
    
        async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
        async with async_session() as s:
            s.add(CasbinRule(ptype="p", v0="alice", v1="data1", v2="read"))
            s.add(CasbinRule(ptype="p", v0="bob", v1="data2", v2="write"))
            s.add(CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="read"))
            s.add(CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="write"))
            s.add(CasbinRule(ptype="g", v0="alice", v1="data2_admin"))
            await s.commit()
    
        e = casbin.AsyncEnforcer("path/to/model.conf", adapter)
        await e.load_policy()
        return e
    
    async def main():
        e = await get_enforcer()
        if e.enforce("alice", "data1", "read"):
            print("alice can read data1")
        else:
            print("alice can not read data1")
    
    asyncio.run(main())
  4. Get started with PyCasbin

    master

    To implement authorization in your application, follow these three steps:

    1. Initialize the Enforcer: Create an enforcer instance by providing a model configuration file and a policy file (or a database adapter).
    2. Enforce Permissions: Call e.enforce(sub, obj, act) before performing a sensitive operation. It returns True if access is permitted and False otherwise.
    3. Manage Permissions at Runtime: Use the provided APIs to manage roles and policies dynamically.
    import casbin
    
    # 1. Initialize the enforcer
    e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv")
    
    # 2. Enforce a request
    sub = "alice"  # the user
    obj = "data1"  # the resource
    act = "read"   # the operation
    
    if e.enforce(sub, obj, act):
        # permit alice to read data1
        pass
    else:
        # deny the request
        pass
    
    # 3. Runtime management example
    roles = e.get_roles_for_user("alice")
  5. Configure Logging in PyCasbin

    master

    PyCasbin uses the standard Python logging module. It calls logging.getLogger() to set up its logger.

    • Default Behavior: If your parent application has not initialized logging, you will not see any PyCasbin log messages. To see logs, you must initialize the logger in your application.
    • Custom Configuration: You can specify a custom logging configuration using the logging_config parameter when enabling logs in PyCasbin.
    • Django Users: For Django integrations, refer to the official Django logging documentation.
    • Standard Python Users: Refer to the standard Python logging.config documentation.
  6. Common Casbin Model and Policy Examples

    master

    PyCasbin supports various access control models. Below is a summary of common models and their corresponding configuration files available in the repository examples:

    ModelModel filePolicy file
    ACLbasic_model.confbasic_policy.csv
    ACL with superuserbasic_model_with_root.confbasic_policy.csv
    ACL without usersbasic_model_without_users.confbasic_policy_without_users.csv
    ACL without resourcesbasic_model_without_resources.confbasic_policy_without_resources.csv
    RBACrbac_model.confrbac_policy.csv
    RBAC with resource rolesrbac_model_with_resource_roles.confrbac_policy_with_resource_roles.csv
    RBAC with domains/tenantsrbac_model_with_domains.confrbac_policy_with_domains.csv
    ABACabac_model.confN/A
    RESTfulkeymatch_model.confkeymatch_policy.csv
    Deny-overriderbac_model_with_deny.confrbac_policy_with_deny.csv
    Prioritypriority_model.confpriority_policy.csv