Casbin.NET Documentation

repository·master·Indexed 23 days ago

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

An open-source access control library for .NET (C#) projects that supports various authorization models including ACL, RBAC, and ABAC. It utilizes the PERM metamodel (Policy, Effect, Request, Matchers) to decouple authorization logic from application code via configuration files and policy sets.

Tokens
4.2K
Snippets
6
Records
13
Agent score
30%

What's inside Casbin.NET

  1. Supported access control models in Casbin.NET

    master

    Casbin.NET supports a wide variety of access control models:

    • ACL (Access Control List)
    • ACL with superuser
    • ACL without users (useful for systems without authentication)
    • ACL without resources (targeting resource types instead of specific instances)
    • RBAC (Role-Based Access Control)
    • RBAC with resource roles (both users and resources can have roles)
    • RBAC with domains/tenants (role sets vary by domain)
    • ABAC (Attribute-Based Access Control) (supports attribute syntax like resource.Owner)
    • RESTful (supports path patterns like /res/* and HTTP methods)
    • Deny-override (deny permissions override allow permissions)
    • Priority (rules can be prioritized like firewall rules)
  2. How Casbin access control models work

    master

    Casbin abstracts access control models using the PERM metamodel:

    1. Policy: The rules that define permissions.
    2. Effect: How the results of the matchers are combined (e.g., some(where (p.eft == allow))).
    3. Request: The definition of the incoming access request (e.g., sub, obj, act).
    4. Matchers: The logic used to match the request against the policy.

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

  3. Compare LoadFilteredPolicy and LoadIncrementalFilteredPolicy

    master

    Choosing between these two methods depends on whether you want to replace or augment your current policy set:

    • LoadFilteredPolicy: Clears all existing policies in the enforcer and replaces them with the new filtered set. Use this when you want to replace the entire policy set with a specific subset.
    • LoadIncrementalFilteredPolicy: Keeps existing policies and appends the new filtered set. Use this when you want to build up a policy set from multiple filtered subsets.
  4. Understand the difference between Casbin and Authentication

    master

    It is important to distinguish between what Casbin does and what it does not do:

    Casbin DOES:

    • Enforce policies in {subject, object, action} form or customized forms.
    • Handle storage of access control models and policies.
    • Manage role-user and role-role mappings (role hierarchy).
    • Support built-in superusers (e.g., root).
    • Provide built-in operators for rule matching (e.g., keyMatch).

    Casbin DOES NOT DO:

    • Authentication: It does not verify usernames or passwords. You must handle user login/identity separately.
    • User/Role Management: It does not manage the master list of users or roles in your system; it only manages the mappings between them for authorization purposes.
  5. Quickstart: Initialize and use an Enforcer

    master

    To start using Casbin, you need to create an Enforcer with a model configuration file and a policy file, then use the Enforce method to check permissions.

    // 1. Initialize the enforcer
    var e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
    
    // 2. Define the request parameters
    var sub = "alice"; // the user
    var obj = "data1"; // the resource
    var act = "read";  // the operation
    
    // 3. Enforce the policy
    if (e.Enforce(sub, obj, act)) {
        // permit alice to read data1
    } else {
        // deny the request
    }
  6. Use Authz middlewares for web frameworks

    master
    Casbin provides authorization (Authz) middlewares designed for integration with various web frameworks. These middlewares automate the enforcement of Casbin policies during the request lifecycle of your web application. For a list of available middlewares and framework-specific integration guides, visit the official Casbin middleware documentation.
  7. Load multiple policy types incrementally

    master

    You can use incremental loading to combine different types of policies (like p and g) or different subjects into a single enforcer instance. This allows for complex permission models where users inherit roles and have direct permissions loaded from different filtered queries.

    using Casbin;
    using Casbin.Model;
    using Casbin.Persist;
    using Casbin.Persist.Adapter.File;
    
    // Setup
    var enforcer = new Enforcer("path/to/model.conf");
    var adapter = new FileAdapter("path/to/policy.csv");
    enforcer.SetAdapter(adapter);
    
    // Load only alice's p policies
    enforcer.LoadFilteredPolicy(
        new PolicyFilter(PermConstants.DefaultPolicyType, 0, Policy.ValuesFrom(new[] { "alice" }))
    );
    
    // Incrementally load the data2_admin role's p policies
    enforcer.LoadIncrementalFilteredPolicy(
        new PolicyFilter(PermConstants.DefaultPolicyType, 0, Policy.ValuesFrom(new[] { "data2_admin" }))
    );
    
    // Incrementally load alice's g policies (role assignments)
    enforcer.LoadIncrementalFilteredPolicy(
        new PolicyFilter(PermConstants.DefaultRoleType, 0, Policy.ValuesFrom(new[] { "alice" }))
    );
    
    // Now alice can access resources through both direct policies and role inheritance
  8. Explore Casbin model and policy examples

    master

    Casbin supports various access control models including ACL, RBAC, ABAC, and RESTful patterns. You can find reference implementations for model configuration files (.conf) and policy data files (.csv) for the following scenarios:

    • ACL (Access Control List): Basic ACL, ACL with superuser, ACL without users, and ACL without resources.
    • RBAC (Role-Based Access Control): Standard RBAC, RBAC with resource roles, RBAC with domains/tenants, and RBAC with deny-override.
    • ABAC (Attribute-Based Access Control): Model-based configuration.
    • RESTful: Using key matching for URL/resource patterns.
    • Other: Priority-based models.
    | Model                     | Model file                                                                                                                       | Policy file                                                                                       |
    | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
    | ACL                       | [basic_model.conf](https://github.com/casbin/casbin/blob/master/examples/basic_model.conf)                                       | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv)                         |
    | ACL with superuser        | [basic_model_with_root.conf](https://github.com/casbin/casbin/blob/master/examples/basic_with_root_model.conf)                   | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_with_root_model.conf)                         |
    | ACL without users         | [basic_model_without_users.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_model.conf)           | [basic_policy_without_users.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_policy.csv)           |
    | ACL without resources     | [basic_model_without_resources.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_model.conf)   | [basic_policy_without_resources.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_policy.csv)   |
    | RBAC                      | [rbac_model.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_model.conf)                                         | [rbac_policy.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_policy.csv)                                         |
    | RBAC with resource roles  | [rbac_model_with_resource_roles.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_model.conf) | [rbac_policy_with_resource_roles.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_policy.csv) |
    | RBAC with domains/tenants | [rbac_model_with_domains.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_model.conf)               | [rbac_policy_with_domains.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_policy.csv)               |
    | ABAC                      | [abac_model.conf](https://github.com/casbin/casbin/blob/master/examples/abac_model.conf)                                         | N/A                                                                                                               |
    | RESTful                   | [keymatch_model.conf](https://github.com/casbin/casbin/blob/master/examples/keymatch_model.conf)                                 | [keymatch_policy.csv](https://github.com/casbin/casbin/blob/master/examples/keymatch_policy.csv)                                 |
    | Deny-override             | [rbac_model_with_deny.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_model.conf)                     | [rbac_policy_with_deny.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_policy.csv)                     |
    | Priority                  | [priority_model.conf](https://github.com/casbin/casbin/blob/master/examples/priority_model.conf)                                 | [priority_policy.csv](https://github.com/casbin/casbin/blob/master/examples/priority_policy.csv)                                 |
  9. Manage user roles at runtime

    master

    Casbin provides APIs to manage permissions and roles while the application is running. For example, you can retrieve all roles assigned to a specific user using GetRolesForUser.

    var roles = e.GetRolesForUser("alice");
    var roles = e.GetRolesForUser("alice")
  10. Use LoadIncrementalFilteredPolicy to append policies

    master

    Use LoadIncrementalFilteredPolicy (or its async counterpart LoadIncrementalFilteredPolicyAsync) to append a filtered set of policies from your adapter without clearing the policies already loaded in the enforcer. This is ideal for building up a policy set from multiple subsets, such as loading different user roles or combining p (permission) and g (role) policies incrementally.

    public static bool LoadIncrementalFilteredPolicy(this IEnforcer enforcer, IPolicyFilter filter)
    public static Task<bool> LoadIncrementalFilteredPolicyAsync(this IEnforcer enforcer, IPolicyFilter filter)
  11. Configure PolicyFilter for subset loading

    master

    The PolicyFilter class defines which subset of policies to load. It requires three parameters:

    1. policyType: The type of policy to filter. Use PermConstants.DefaultPolicyType for "p" policies or PermConstants.DefaultRoleType for "g" policies.
    2. fieldIndex: The 0-based index of the field to start filtering on.
    3. values: The specific values to filter by (created via Policy.ValuesFrom).
    // Filter p policies where the first field (subject) is "alice"
    new PolicyFilter(PermConstants.DefaultPolicyType, 0, Policy.ValuesFrom(new[] { "alice" }))
    
    // Filter g policies where the first field (user) is "alice"
    new PolicyFilter(PermConstants.DefaultRoleType, 0, Policy.ValuesFrom(new[] { "alice" }))
    
    // Filter p policies where the second field (object) is "data1"
    new PolicyFilter(PermConstants.DefaultPolicyType, 1, Policy.ValuesFrom(new[] { "data1" }))