### Install casbin-ucon Extension Source: https://casbin.org/docs/ucon Use 'go get' to install the casbin-ucon library. This is the first step to integrate UCON functionality. ```bash go get github.com/casbin/casbin-ucon ``` -------------------------------- ### Install Casbin v3 for Go Source: https://casbin.org/docs/get-started Use 'go get' to install or update the Casbin v3 library for Go projects. This command fetches the latest version of the library. ```go go get github.com/casbin/casbin/v3 ``` ```go go get -u github.com/casbin/casbin/v3 ``` -------------------------------- ### Build and Install Casbin-CPP Source: https://casbin.org/docs/get-started Compile and install the Casbin C++ library from source. This involves cloning the repository, generating build files with CMake, and then building and installing the library. ```bash # Download source git clone https://github.com/casbin/casbin-cpp.git # Generate project files cd casbin-cpp && mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release # Build and install casbin cmake --build . --config Release --target casbin install -j 10 ``` -------------------------------- ### RBAC API Examples Source: https://casbin.org/docs/api-overview Demonstrates common RBAC operations such as getting roles for a user, getting users for a role, checking role assignments, and managing permissions. ```APIDOC ## RBAC API This section provides examples of how to use the RBAC helper functions. ### Get Roles for User Retrieves all roles assigned to a specific user. ```go roles, err := enforcer.GetRolesForUser("amber") fmt.Println(roles) // Expected output: [admin] ``` ### Get Users for Role Retrieves all users assigned to a specific role. ```go users, err := enforcer.GetUsersForRole("admin") fmt.Println(users) // Expected output: [amber abc] ``` ### Check Role for User Checks if a user has a specific role assigned. ```go hasRole := enforcer.HasRoleForUser("amber", "admin") fmt.Println(hasRole) // Expected output: true ``` ### Enforce Policy Evaluates a request against the loaded policy. ```go result := enforcer.Enforce("bob", "data2", "write") fmt.Println(result) // Expected output: true ``` ### Delete Permission Removes a specific permission from the policy for all users. ```go enforcer.DeletePermission("data2", "write") result := enforcer.Enforce("bob", "data2", "write") fmt.Println(result) // Expected output: false ``` ### Delete Permission for User Removes a specific permission for a particular user. ```go enforcer.DeletePermissionForUser("alice", "data1", "read") ``` ``` -------------------------------- ### Install kong-authz Plugin Source: https://casbin.org/docs/kong-authz Installs the kong-authz plugin from its GitHub repository using LuaRocks. ```bash sudo luarocks install https://raw.githubusercontent.com/casbin-lua/kong-authz/master/kong-authz-0.0.1-1.rockspec ``` -------------------------------- ### Create Route for Example Service Source: https://casbin.org/docs/kong-authz Creates a route for the 'example-service' with a specified host. ```bash curl -i -X POST \ --url http://localhost:8001/services/example-service/routes \ --data 'hosts[]=example.com' ``` -------------------------------- ### Install Casbin.js with npm Source: https://casbin.org/docs/frontend Install Casbin.js and the core Casbin library using npm. Alternatively, use yarn. ```bash npm install casbin.js npm install casbin ``` ```bash yarn add casbin.js ``` -------------------------------- ### Create Example Service Source: https://casbin.org/docs/kong-authz Creates a sample service named 'example-service' for testing purposes. ```bash curl -i -X POST \ --url http://localhost:8001/services/ \ --data 'name=example-service' \ --data 'url=http://mockbin.org' ``` -------------------------------- ### Install Rust Casbin CLI from crates.io Source: https://casbin.org/docs/command-line-tools Install the casbin-rust-cli directly from crates.io using cargo. ```bash cargo install casbin-rust-cli ``` -------------------------------- ### Create Python Enforcer with FileAdapter Source: https://casbin.org/docs/get-started Initialize a Casbin Enforcer in Python by providing the paths to the model and policy files. This example assumes the 'casbin' library is installed. ```python import casbin e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv") ``` -------------------------------- ### Apply kong-authz Plugin to Example Service Source: https://casbin.org/docs/kong-authz Applies the kong-authz plugin to the 'example-service' with file-based policy configuration. ```bash curl -i -X POST \ --url http://localhost:8001/services/example-service/plugins/ \ --data 'name=kong-authz' \ --data 'config.model_path=/path/to/authz_model.conf' \ --data 'config.policy_path=/path/to/authz_policy.csv' \ --data 'config.username=user' ``` -------------------------------- ### Example Policy and Role Assignment Source: https://casbin.org/docs/rbac Stores user-role mappings in the policy. This example shows a user 'alice' being assigned the role 'data2_admin'. ```ini p, data2_admin, data2, read g, alice, data2_admin ``` -------------------------------- ### Example Policy with Domains Source: https://casbin.org/docs/rbac-with-domains Illustrates a policy where roles and permissions are scoped to specific domains. ```ini p, admin, tenant1, data1, read p, admin, tenant2, data2, read g, alice, admin, tenant1 g, alice, user, tenant2 ``` -------------------------------- ### Install Python Casbin CLI Dependencies Source: https://casbin.org/docs/command-line-tools Navigate to the cloned directory and install the required dependencies for the Python CLI. ```bash cd casbin-python-cli pip install -r requirements.txt ``` -------------------------------- ### Backend Endpoint for Frontend Permissions (Go Beego) Source: https://casbin.org/docs/frontend Implement a backend endpoint using Go Beego to generate permission objects for the frontend. This example shows router setup and controller logic to fetch user permissions. ```go // Router beego.Router("api/casbin", &controllers.APIController{}, "GET:GetFrontendPermission") // Controller func (c *APIController) GetFrontendPermission() { // Get the visitor from the GET parameters. (The key is "casbin_subject") visitor := c.Input().Get("casbin_subject") // `e` is an initialized instance of Casbin Enforcer c.Data["perm"] = casbin.CasbinJsGetPermissionForUser(e, visitor) // Pass the data to the frontend. c.ServeJSON() } ``` -------------------------------- ### Clone .NET Casbin CLI Repository Source: https://casbin.org/docs/command-line-tools Clone the casbin-dotnet-cli repository to get started with the .NET command-line tool. ```bash git clone https://github.com/casbin-net/casbin-dotnet-cli.git ``` -------------------------------- ### Clone Go Casbin CLI Repository Source: https://casbin.org/docs/command-line-tools Clone the casbin-go-cli repository to get started with the Go command-line tool. ```bash git clone https://github.com/casbin/casbin-go-cli.git ``` -------------------------------- ### Kubernetes Deployment YAML Example Source: https://casbin.org/docs/k8s-gatekeeper An example of a Kubernetes Deployment resource definition for an Nginx pod. This YAML is used to demonstrate how an admission request is structured. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: selector: matchLabels: app: nginx replicas: 1 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.1 ports: - containerPort: 80 ``` -------------------------------- ### Example Policy in CSV Format Source: https://casbin.org/docs/policy-storage This CSV formatted policy demonstrates a typical structure for storing roles and permissions. It serves as an example for database layout. ```csv p, data2_admin, data2, read p, data2_admin, data2, write g, alice, admin ``` -------------------------------- ### Install Casbin for Python Source: https://casbin.org/docs/get-started Install the Casbin library for Python projects using pip. This command fetches and installs the latest version of the package. ```bash pip install casbin ``` -------------------------------- ### BLP Model Request Examples Source: https://casbin.org/docs/blp Illustrates various read and write request scenarios under the BLP model, demonstrating allowed and denied operations based on security levels. These examples highlight the 'no read up' and 'no write down' principles. ```text alice, 3, data1, 1, read # alice (level 3) reads data1 (level 1) - ALLOWED bob, 2, data2, 2, read # bob (level 2) reads data2 (level 2) - ALLOWED charlie, 1, data1, 1, read # charlie (level 1) reads data1 (level 1) - ALLOWED bob, 2, data3, 3, read # bob (level 2) reads data3 (level 3) - DENIED (No Read Up) charlie, 1, data2, 2, read # charlie (level 1) reads data2 (level 2) - DENIED (No Read Up) alice, 3, data3, 3, write # alice (level 3) writes data3 (level 3) - ALLOWED bob, 2, data3, 3, write # bob (level 2) writes data3 (level 3) - ALLOWED charlie, 1, data2, 2, write # charlie (level 1) writes data2 (level 2) - ALLOWED alice, 3, data1, 1, write # alice (level 3) writes data1 (level 1) - DENIED (No Write Down) bob, 2, data1, 1, write # bob (level 2) writes data1 (level 1) - DENIED (No Write Down) ``` -------------------------------- ### Install Casbin Lua Module Source: https://casbin.org/docs/kong-authz Installs the latest Casbin release from LuaRocks. ```bash sudo luarocks install casbin ``` -------------------------------- ### Install Casbin System Dependencies (apt) Source: https://casbin.org/docs/kong-authz Installs necessary system dependencies for Casbin on Debian-based systems using apt. ```bash sudo apt install gcc libpcre3 libpcre3-dev ``` -------------------------------- ### Example Casbin Policy File Source: https://casbin.org/docs/menu-permissions This policy file defines role-menu permissions, user-role assignments, and menu hierarchy. It includes examples of explicit allow/deny rules and role inheritance. ```casbin p, ROLE_ROOT, SystemMenu, read, allow p, ROLE_ROOT, AdminMenu, read, allow p, ROLE_ROOT, UserMenu, read, deny p, ROLE_ADMIN, UserMenu, read, allow p, ROLE_ADMIN, AdminMenu, read, allow p, ROLE_ADMIN, AdminSubMenu_deny, read, deny p, ROLE_USER, UserSubMenu_allow, read, allow g, user, ROLE_USER g, admin, ROLE_ADMIN g, root, ROLE_ROOT g, ROLE_ADMIN, ROLE_USER g2, UserSubMenu_allow, UserMenu g2, UserSubMenu_deny, UserMenu g2, UserSubSubMenu, UserSubMenu_allow g2, AdminSubMenu_allow, AdminMenu g2, AdminSubMenu_deny, AdminMenu g2, (NULL), SystemMenu ``` -------------------------------- ### Install Casbin System Dependencies (Alpine) Source: https://casbin.org/docs/kong-authz Installs necessary system dependencies for Casbin on Alpine-based systems using apk. ```bash sudo apk add gcc pcre pcre-dev libc-dev ``` -------------------------------- ### Install Casbin for Lua Source: https://casbin.org/docs/get-started Install the Casbin Lua rock using LuaRocks. If you encounter permission errors, use the '--local' flag to install to your user's local directory. ```bash luarocks install casbin ``` ```bash luarocks install casbin --local ``` -------------------------------- ### KeyGet2 Function Example Source: https://casbin.org/docs/function Illustrates the KeyGet2 function for extracting a named key from a URL using a ':' pattern. ```go KeyGet2("/resource1/action", "/:res/action", "res") ``` -------------------------------- ### KeyGet3 Function Example Source: https://casbin.org/docs/function Shows the KeyGet3 function for extracting a named key from a URL using a '{}' pattern. ```go KeyGet3("/resource1_admin/action", "/{res}_admin/*", "res") ``` -------------------------------- ### Example Casbin Log Output Source: https://casbin.org/docs/log-error This is an example of the output generated by Casbin's default logger when a request is processed. ```text 2017/07/15 19:43:56 [Request: alice, data1, read ---> true] ``` -------------------------------- ### Get Implicit Resources for a User (Go) Source: https://casbin.org/docs/rbac-api Returns all policies that apply to a user, including those inherited through roles. Use this to get a complete list of resources a user can interact with. ```go resources, err := e.GetImplicitResourcesForUser("alice") ``` -------------------------------- ### Apply Envoy Configuration Source: https://casbin.org/docs/envoy Start Envoy with the authorization configuration. Envoy will then route requests through the authorization middleware. ```bash envoy -c authz.yaml -l info ``` -------------------------------- ### ReBAC Policy and Relationship Examples Source: https://casbin.org/docs/rebac Illustrates ReBAC policy enforcement with concrete examples. It shows a permission rule, a user-resource-role assignment, and a resource-type assignment. ```casbin # Permission definition: The "collaborator" role can read files of type "doc" p, collaborator, doc, read # User-Resource-Role Relationship: alice is a collaborator of doc1 g, alice, doc1, collaborator # Resource-Type Relationship: doc1 is of type "doc" g2, doc1, doc ``` -------------------------------- ### Biba Model Request Examples Source: https://casbin.org/docs/biba Illustrates various access control scenarios under the Biba model, demonstrating allowed and denied operations based on integrity levels for read and write actions. These examples highlight the 'no read down' and 'no write up' policies. ```text alice, 3, data1, 1, read # alice (level 3) reads data1 (level 1) - DENIED (No Read Down) bob, 2, data2, 2, read # bob (level 2) reads data2 (level 2) - ALLOWED charlie, 1, data1, 1, read # charlie (level 1) reads data1 (level 1) - ALLOWED bob, 2, data3, 3, read # bob (level 2) reads data3 (level 3) - ALLOWED charlie, 1, data2, 2, read # charlie (level 1) reads data2 (level 2) - ALLOWED alice, 3, data3, 3, write # alice (level 3) writes data3 (level 3) - ALLOWED bob, 2, data3, 3, write # bob (level 2) writes data3 (level 3) - DENIED (No Write Up) charlie, 1, data2, 2, write # charlie (level 1) writes data2 (level 2) - DENIED (No Write Up) alice, 3, data1, 1, write # alice (level 3) writes data1 (level 1) - ALLOWED bob, 2, data1, 1, write # bob (level 2) writes data1 (level 1) - ALLOWED ``` -------------------------------- ### OrBAC Enforcement Example in Go Source: https://casbin.org/docs/orbac Demonstrates how to use the Casbin enforcer with an OrBAC model and policy to enforce access control. ```go import "github.com/casbin/casbin/v3" e, _ := casbin.NewEnforcer("examples/orbac_model.conf", "examples/orbac_policy.csv") // alice is a manager in org1, can read and write documents ok, _ := e.Enforce("alice", "org1", "data1", "read") // true ok, _ = e.Enforce("alice", "org1", "data1", "write") // true // bob is an employee in org1, can only read documents ok, _ = e.Enforce("bob", "org1", "data1", "read") // true ok, _ = e.Enforce("bob", "org1", "data1", "write") // false // charlie is a manager in org2, can read and write reports ok, _ = e.Enforce("charlie", "org2", "report1", "read") // true ok, _ = e.Enforce("charlie", "org2", "report1", "write") // true // Cross-organization access is denied ok, _ = e.Enforce("alice", "org2", "report1", "read") // false ok, _ = e.Enforce("charlie", "org1", "data1", "read") // false ``` -------------------------------- ### Request Examples for Explicit Priority Source: https://casbin.org/docs/priority-model Illustrates how requests are evaluated based on the explicit priority defined in the policies. ```text alice, data1, write --> true // because `p, 1, alice, data1, write, allow` has the highest priority bob, data2, read --> false bob, data2, write --> true // because bob has the role of `data2_allow_group` which has the right to write data2, and there's no deny policy with higher priority ``` -------------------------------- ### Install Internal Webhook CRD Resources Source: https://casbin.org/docs/k8s-gatekeeper Installs the Custom Resource Definitions (CRDs) required for Casbin models and policies in an internal webhook setup. ```bash kubectl apply -f config/auth.casbin.org_casbinmodels.yaml kubectl apply -f config/auth.casbin.org_casbinpolicies.yaml ``` -------------------------------- ### Launch Authorization Server Source: https://casbin.org/docs/envoy Build and launch the authorization server using Go. Ensure dependencies are managed via go.mod. ```bash go build . ./authz ``` -------------------------------- ### Clone Python Casbin CLI Repository Source: https://casbin.org/docs/command-line-tools Clone the casbin-python-cli repository to get started with the Python command-line tool. ```bash git clone https://github.com/casbin/casbin-python-cli.git ``` -------------------------------- ### KeyGet Function Example (Two-Parameter Form) Source: https://casbin.org/docs/function Demonstrates the usage of the KeyGet function with two parameters to extract a value from a URL based on a pattern. ```go KeyGet("/resource1/action", "/*") ``` -------------------------------- ### Clone Java Casbin CLI Repository Source: https://casbin.org/docs/command-line-tools Clone the casbin-java-cli repository to get started with the Java command-line tool. ```bash git clone https://github.com/jcasbin/casbin-java-cli.git ``` -------------------------------- ### Use Custom EnforceContext (Java) Source: https://casbin.org/docs/syntax-for-models Illustrates the usage of a custom EnforceContext in Java, demonstrating how to initialize it with a suffix and enforce policies. ```java // Pass in a suffix as a parameter to NewEnforceContext, such as 2 or 3, and it will create r2, p2, etc. EnforceContext enforceContext = new EnforceContext("2"); // You can also specify a certain type individually enforceContext.seteType("e"); // Don't pass in EnforceContext; the default is r, p, e, m e.enforce("alice", "data2", "read"); // true // Pass in EnforceContext // TestEvalRule is located in https://github.com/casbin/jcasbin/blob/master/src/test/java/org/casbin/jcasbin/main/AbacAPIUnitTest.java#L56 e.enforce(enforceContext, new AbacAPIUnitTest.TestEvalRule("alice", 70), "/data1", "read"); // false e.enforce(enforceContext, new AbacAPIUnitTest.TestEvalRule("alice", 30), "/data1", "read"); // true ``` -------------------------------- ### Get All Actions Source: https://casbin.org/docs/management-api Retrieves all actions defined in the current policy. Use this to understand the set of operations that can be performed. ```go allActions := e.GetAllActions() ``` ```javascript const allActions = await e.getAllActions() ``` ```php $allActions = $e->getAllActions(); ``` ```python all_actions = e.get_all_actions() ``` ```csharp var allActions = e.GetAllActions(); ``` ```rust let all_actions = e.get_all_actions(); ``` ```java List allActions = e.getAllActions(); ``` -------------------------------- ### Update Adapter Usage Example Source: https://casbin.org/docs/adapters Demonstrates how to use the UpdateAdapter methods to modify policy rules. Requires an initialized Casbin enforcer and an adapter implementing UpdateAdapter. ```go import ( "github.com/casbin/casbin/v3" "github.com/casbin/gorm-adapter/v3" ) a, _ := gormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/") e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) // Update a single policy // Change: p, alice, data1, read -> p, alice, data1, write e.UpdatePolicy( []string{"alice", "data1", "read"}, []string{"alice", "data1", "write"}, ) // Update multiple policies at once e.UpdatePolicies( [][]string{{"alice", "data1", "write"}, {"bob", "data2", "read"}}, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}, ) // Update all policies matching a filter e.UpdateFilteredPolicies( [][]string{{"alice", "data1", "write"}}, 0, "alice", "data1", "read", ) ``` -------------------------------- ### Casbin Policy with Time-Based Role Assignments Source: https://casbin.org/docs/rbac-with-conditions Example policy demonstrating role assignments with specific start and end times, or using '_' for indefinite validity. ```conf p, alice, data1, read p, data2_admin, data2, write p, data3_admin, data3, read p, data4_admin, data4, write p, data5_admin, data5, read p, data6_admin, data6, write p, data7_admin, data7, read p, data8_admin, data8, write g, alice, data2_admin, 0000-01-01 00:00:00, 0000-01-02 00:00:00 g, alice, data3_admin, 0000-01-01 00:00:00, 9999-12-30 00:00:00 g, alice, data4_admin, _, _ g, alice, data5_admin, _, 9999-12-30 00:00:00 g, alice, data6_admin, _, 0000-01-02 00:00:00 g, alice, data7_admin, 0000-01-01 00:00:00, _ g, alice, data8_admin, 9999-12-30 00:00:00, _ ``` -------------------------------- ### Get Users for Role Source: https://casbin.org/docs/rbac-api Retrieve all users assigned to a specific role. Supports multiple languages. ```go res := e.GetUsersForRole("data1_admin") ``` ```javascript const res = await e.getUsersForRole('data1_admin') ``` ```php $res = $e->getUsersForRole("data1_admin"); ``` ```python users = e.get_users_for_role("data1_admin") ``` ```csharp var res = e.GetUsersForRole("data1_admin"); ``` ```rust let users = e.get_users_for_role("data1_admin", None); // No domain ``` ```java List res = e.getUsersForRole("data1_admin"); ``` -------------------------------- ### Build .NET Casbin CLI Project Source: https://casbin.org/docs/command-line-tools Navigate to the cloned directory and build the .NET Casbin CLI project. ```bash cd casbin-dotnet-cli dotnet build ``` -------------------------------- ### Initialize Enforcer Instance Source: https://casbin.org/docs/rbac-api Instantiate an Enforcer with model and policy configuration files. Supports multiple languages. ```go e, err := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") ``` ```javascript const e = await newEnforcer('examples/rbac_model.conf', 'examples/rbac_policy.csv') ``` ```php $e = new Enforcer('examples/rbac_model.conf', 'examples/rbac_policy.csv'); ``` ```python e = casbin.Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") ``` ```csharp var e = new Enforcer("path/to/model.conf", "path/to/policy.csv"); ``` ```rust let mut e = Enforcer::new("examples/rbac_model.conf", "examples/rbac_policy.csv").await?; ``` ```java Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv"); ``` -------------------------------- ### Get Implicit Users for Resource by Domain Source: https://casbin.org/docs/rbac-with-domains-api Finds users who have implicit permissions on a given resource within a specific domain, typically through their assigned roles. The example policy illustrates how roles grant access. ```plaintext p, admin, domain1, data1, read p, admin, domain1, data1, write p, admin, domain2, data2, read p, admin, domain2, data2, write g, alice, admin, domain1 g, bob, admin, domain2 ``` ```go ImplicitUsers, err := e.GetImplicitUsersForResourceByDomain("data1", "domain1") ``` -------------------------------- ### Example ACL Policy Source: https://casbin.org/docs/how-it-works Sample policy entries for the minimal ACL model, defining permissions for users 'alice' and 'bob'. ```csv p, alice, data1, read p, bob, data2, write ``` -------------------------------- ### Use Custom EnforceContext (Go) Source: https://casbin.org/docs/syntax-for-models Demonstrates how to create and use a custom EnforceContext in Go to enforce policies with specific section types (e.g., r2, p2). ```go // Pass in a suffix as a parameter to NewEnforceContext, such as 2 or 3, and it will create r2, p2, etc. enforceContext := NewEnforceContext("2") // You can also specify a certain type individually enforceContext.EType = "e" // Don't pass in EnforceContext; the default is r, p, e, m e.Enforce("alice", "data2", "read") // true // Pass in EnforceContext e.Enforce(enforceContext, struct{ Age int }{Age: 70}, "/data1", "read") //false e.Enforce(enforceContext, struct{ Age int }{Age: 30}, "/data1", "read") //true ``` -------------------------------- ### Build Go Casbin CLI Source: https://casbin.org/docs/command-line-tools Navigate to the cloned directory and build the casbin-go-cli executable. ```bash cd casbin-go-cli go build -o casbin ``` -------------------------------- ### Initialize MySQL Adapter Enforcer (Go) Source: https://casbin.org/docs/adapters Initializes a Casbin enforcer using a MySQL adapter. Requires database connection details. ```go import ( "github.com/casbin/casbin/v3" "github.com/casbin/mysql-adapter" ) a := mysqladapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/") e := casbin.NewEnforcer("examples/basic_model.conf", a) ``` -------------------------------- ### Run Go Benchmarks Source: https://casbin.org/docs/benchmark Execute Go benchmarks using `go test -bench=. -benchmem`. This command measures time and memory overhead per Enforce() call. ```bash go test -bench=. -benchmem ``` -------------------------------- ### Get Policy Source: https://casbin.org/docs/management-api Retrieves all authorization rules from the policy. Use this to get the complete set of rules. ```go policy = e.GetPolicy() ``` ```javascript const policy = await e.getPolicy() ``` ```php $policy = $e->getPolicy(); ``` ```python policy = e.get_policy() ``` ```csharp var policy = e.GetPolicy(); ``` ```rust let policy = e.get_policy(); ``` ```java List> policy = e.getPolicy(); ``` -------------------------------- ### Initialize Enforcer (Go) Source: https://casbin.org/docs/management-api Initializes a new Enforcer instance with a model configuration and a policy file. ```go e, err := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") ``` -------------------------------- ### Get All Objects Source: https://casbin.org/docs/management-api Retrieves all objects from the current policy. Use this to get a list of all unique resources that are being accessed. ```go allObjects := e.GetAllObjects() ``` ```javascript const allObjects = await e.getAllObjects() ``` ```php $allObjects = $e->getAllObjects(); ``` ```python all_objects = e.get_all_objects() ``` ```csharp var allObjects = e.GetAllObjects(); ``` ```rust let all_objects = e.get_all_objects(); ``` ```java List allObjects = e.getAllObjects(); ``` -------------------------------- ### Build Rust Casbin CLI from Source Source: https://casbin.org/docs/command-line-tools Navigate to the cloned directory and build the casbin-rust-cli with release optimizations. ```bash cd casbin-rust-cli cargo build --release ``` -------------------------------- ### Initialize File Adapter Enforcer with Adapter Instance (Go) Source: https://casbin.org/docs/adapters Initializes a Casbin enforcer by first creating a file adapter instance and then passing it to the enforcer. ```go import ( "github.com/casbin/casbin/v3" fileadapter "github.com/casbin/casbin/v3/persist/file-adapter" ) a := fileadapter.NewAdapter("examples/basic_policy.csv") e := casbin.NewEnforcer("examples/basic_model.conf", a) ``` -------------------------------- ### Get All Roles Source: https://casbin.org/docs/management-api Retrieves all roles defined in the current policy. Use this to get a list of all user groups or roles. ```go allRoles = e.GetAllRoles() ``` ```javascript const allRoles = await e.getAllRoles() ``` ```php $allRoles = $e->getAllRoles(); ``` ```python all_roles = e.get_all_roles() ``` ```csharp var allRoles = e.GetAllRoles(); ``` ```rust let all_roles = e.get_all_roles(); ``` ```java List allRoles = e.getAllRoles(); ``` -------------------------------- ### Prepare and Run External Webhook Source: https://casbin.org/docs/k8s-gatekeeper Prepares the Go modules and runs the K8s-gatekeeper external webhook. Ensure your hosts file is updated to point 'webhook.domain.local' to the correct IP address. Kubernetes requires HTTPS for admission webhooks. ```bash go mod tidy go mod vendor go run cmd/webhook/main.go ``` -------------------------------- ### Policy CSV for Subject Priority Example Source: https://casbin.org/docs/priority-model CSV data for a subject priority example, defining policies and role hierarchy. ```csv p, root, data1, read, deny p, admin, data1, read, deny p, editor, data1, read, deny p, subscriber, data1, read, deny p, jane, data1, read, allow p, alice, data1, read, allow g, admin, root g, editor, admin g, subscriber, admin g, jane, editor g, alice, subscriber ``` -------------------------------- ### Install K8s-gatekeeper via Helm Source: https://casbin.org/docs/k8s-gatekeeper Installs K8s-gatekeeper using Helm. This command assumes the Helm chart is available in the current directory. ```bash helm install k8sgatekeeper ./k8sgatekeeper ``` -------------------------------- ### Initialize and Configure UCON Enforcer in Go Source: https://casbin.org/docs/ucon This snippet shows how to initialize a standard Casbin enforcer, wrap it with UCON functionality, and add custom conditions and obligations. It also demonstrates creating and enforcing a UCON session. ```go // Import the required packages import ( "github.com/casbin/casbin/v3" "github.com/casbin/casbin-ucon" "fmt" "time" ) func main() { // Create standard Casbin enforcer e, _ := casbin.NewEnforcer("model.conf", "policy.csv") // Wrap with UCON functionality uconE := ucon.NewUconEnforcer(e) // Add conditions condition := &ucon.Condition{ ID: "location_condition", Name: "location", Kind: "always", Expr: "office", } uconE.AddCondition(condition) // Add obligations obligation := &ucon.Obligation{ ID: "post_log", Name: "access_logging", Kind: "post", Expr: "log_level:detailed", } uconE.AddObligation(obligation) // Create a session sessionID, _ := uconE.CreateSession("alice", "read", "document1", map[string]interface{}{ "location": "office", "log_level": "detailed", }) // UCON session-based enforcement session, err := uconE.EnforceWithSession(sessionID) if session == nil { // refused fmt.Println("session refused because: ", err) } // Monitor session status go func() { for { if !session.IfActive() { if session.GetStopReason() == ucon.NormalStopReason { break } //TODO //decide how to handle session termination yourself // For example, clean up resources, close connections, write logs, notify the frontend, etc. fmt.Printf("%s %s %s is stopped because: %s\n", session.GetSubject(), session.GetAction(), session.GetObject(), session.GetStopReason()) break } time.Sleep(200 * time.Millisecond) } }() // You can update attributes during the session // session.UpdateAttribute("location", "home") // Stop the session when done _ = uconE.StopMonitoring(sessionID) } ``` -------------------------------- ### LBAC Example Requests Source: https://casbin.org/docs/lbac Demonstrates various read and write operations with different subject and object security levels, illustrating allowed and denied scenarios based on LBAC rules. ```casbin # Normal read operations (ALLOWED) admin, 5, 5, file_topsecret, 3, 3, read # admin (conf:5, int:5) reads file_topsecret (conf:3, int:3) - ALLOWED manager, 4, 4, file_secret, 4, 2, read # manager (conf:4, int:4) reads file_secret (conf:4, int:2) - ALLOWED staff, 3, 3, file_internal, 2, 3, read # staff (conf:3, int:3) reads file_internal (conf:2, int:3) - ALLOWED guest, 2, 2, file_public, 2, 2, read # guest (conf:2, int:2) reads file_public (conf:2, int:2) - ALLOWED # Read operation violations (DENIED) staff, 3, 3, file_secret, 4, 2, read # staff (conf:3, int:3) reads file_secret (conf:4, int:2) - DENIED (conf < obj.conf) manager, 4, 4, file_sensitive, 3, 5, read # manager (conf:4, int:4) reads file_sensitive (conf:3, int:5) - DENIED (int < obj.int) guest, 2, 2, file_internal, 3, 1, read # guest (conf:2, int:2) reads file_internal (conf:3, int:1) - DENIED (conf < obj.conf) staff, 3, 3, file_protected, 1, 4, read # staff (conf:3, int:3) reads file_protected (conf:1, int:4) - DENIED (int < obj.int) # Normal write operations (ALLOWED) guest, 2, 2, file_public, 2, 2, write # guest (conf:2, int:2) writes file_public (conf:2, int:2) - ALLOWED staff, 3, 3, file_internal, 5, 4, write # staff (conf:3, int:3) writes file_internal (conf:5, int:4) - ALLOWED manager, 4, 4, file_secret, 4, 5, write # manager (conf:4, int:4) writes file_secret (conf:4, int:5) - ALLOWED admin, 5, 5, file_archive, 5, 5, write # admin (conf:5, int:5) writes file_archive (conf:5, int:5) - ALLOWED # Write operation violations (DENIED) manager, 4, 4, file_internal, 3, 5, write # manager (conf:4, int:4) writes file_internal (conf:3, int:5) - DENIED (conf > obj.conf) staff, 3, 3, file_public, 2, 2, write # staff (conf:3, int:3) writes file_public (conf:2, int:2) - DENIED (both > obj) admin, 5, 5, file_secret, 5, 4, write # admin (conf:5, int:5) writes file_secret (conf:5, int:4) - DENIED (int > obj.int) guest, 2, 2, file_private, 1, 3, write # guest (conf:2, int:2) writes file_private (conf:1, int:3) - DENIED (conf > obj.conf) ``` -------------------------------- ### Configure Auto-Save with Xorm Adapter Source: https://casbin.org/docs/adapters Example demonstrating how to enable/disable Auto-Save functionality with the xorm adapter. Auto-Save persists individual policy changes directly to storage. ```go import ( "github.com/casbin/casbin/v3" "github.com/casbin/xorm-adapter" _ "github.com/go-sql-driver/mysql" ) // AutoSave is enabled by default when using compatible adapters with enforcers. a := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/?charset=utf8&parseTime=True&loc=Local") e := casbin.NewEnforcer("examples/basic_model.conf", a) // Disable AutoSave. e.EnableAutoSave(false) // Policy changes affect only the in-memory enforcer, // not the storage. e.AddPolicy(...) e.RemovePolicy(...) // Enable AutoSave. e.EnableAutoSave(true) // Policy changes now persist to storage // in addition to updating the in-memory enforcer. e.AddPolicy(...) e.RemovePolicy(...) ``` -------------------------------- ### Initialize File Adapter Enforcer with Adapter Instance (PHP) Source: https://casbin.org/docs/adapters Initializes a Casbin enforcer by first creating a file adapter instance and then passing it to the enforcer. ```php use Casbin\Enforcer; use Casbin\Persist\Adapters\FileAdapter; $a = new FileAdapter('examples/basic_policy.csv'); $e = new Enforcer('examples/basic_model.conf', $a); ``` -------------------------------- ### Install Casbin via Yarn Source: https://casbin.org/docs/get-started Install the Casbin package for Node.js projects using Yarn. This command adds the Casbin library to your project's dependencies. ```bash # Yarn yarn add casbin ``` -------------------------------- ### Install Casbin via NPM Source: https://casbin.org/docs/get-started Install the Casbin package for Node.js projects using NPM. This command adds the Casbin library to your project's dependencies. ```bash # NPM npm install casbin --save ``` -------------------------------- ### Get Implicit Resources for a User (Java) Source: https://casbin.org/docs/rbac-api Returns all policies that apply to a user, including those inherited through roles. Use this to get a complete list of resources a user can interact with. ```java var resources = e.GetImplicitResourcesForUser("alice"); ``` -------------------------------- ### Switch to a New Adapter Source: https://casbin.org/docs/adapters Change the active storage adapter for the enforcer. ```go e.SetAdapter(B) ``` -------------------------------- ### Initialize Enforcer (JavaScript) Source: https://casbin.org/docs/management-api Initializes a new Enforcer instance with a model configuration and a policy file using async/await. ```javascript const e = await newEnforcer('examples/rbac_model.conf', 'examples/rbac_policy.csv') ``` -------------------------------- ### GetNamedImplicitRolesForUser Source: https://casbin.org/docs/rbac-api Gets implicit roles that a user has by named policy. ```APIDOC ## GetNamedImplicitRolesForUser() ### Description Gets implicit roles that a user has by named policy. ### Method Not specified (example shows direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go var roles = e.GetNamedImplicitRolesForUser("g", "alice") ``` ### Response #### Success Response (List) - **roles** (List) - A list of implicit roles the user possesses for the specified named policy. ``` -------------------------------- ### Initialize MySQL Adapter Enforcer (PHP) Source: https://casbin.org/docs/adapters Initializes a Casbin enforcer using a MySQL adapter with DBAL. Requires specific database configuration. ```php // https://github.com/php-casbin/dbal-adapter use Casbin\Enforcer; use CasbinAdapter\DBAL\Adapter as DatabaseAdapter; $config = [ // Either 'driver' with one of the following values: // pdo_mysql,pdo_sqlite,pdo_pgsql,pdo_oci (unstable),pdo_sqlsrv,pdo_sqlsrv, // mysqli,sqlanywhere,sqlsrv,ibm_db2 (unstable),drizzle_pdo_mysql 'driver' => 'pdo_mysql', 'host' => '127.0.0.1', 'dbname' => 'test', 'user' => 'root', 'password' => '', 'port' => '3306', ]; $a = DatabaseAdapter::newAdapter($config); $e = new Enforcer('examples/basic_model.conf', $a); ``` -------------------------------- ### GetNamedPermissionsForUser Source: https://casbin.org/docs/rbac-api Gets permissions for a user or role by named policy. ```APIDOC ## GetNamedPermissionsForUser() ### Description Gets permissions for a user or role by named policy. ### Method Not specified (example shows direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go permissions, err := e.GetNamedPermissionsForUser("p", "alice") ``` ### Response #### Success Response (List>) - **permissions** (List>) - A list of permissions associated with the user or role for the specified named policy. ``` -------------------------------- ### Initialize Enforcer (JavaScript - Alternative) Source: https://casbin.org/docs/management-api Initializes a new Enforcer instance with a model configuration and a policy file. ```javascript var e = new Enforcer("path/to/model.conf", "path/to/policy.csv"); ``` -------------------------------- ### GetImplicitUsersForRole Source: https://casbin.org/docs/rbac-api Gets all users inheriting a role, including indirect users. ```APIDOC ## GetImplicitUsersForRole() ### Description Gets all users inheriting the role. Compared to GetUsersForRole(), this function retrieves indirect users. ### Method Not specified (example shows direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go users := e.GetImplicitUsersForRole("role:user") ``` ### Response #### Success Response (List) - **users** (List) - A list of users who implicitly inherit the specified role. ``` -------------------------------- ### GetImplicitRolesForUser Source: https://casbin.org/docs/rbac-api Gets all implicit roles that a user has, including indirect roles. ```APIDOC ## GetImplicitRolesForUser() ### Description Gets all implicit roles that a user has. Compared to GetRolesForUser(), this function retrieves indirect roles besides direct roles. ### Method Not specified (example shows direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go var implicitRoles = e.GetImplicitRolesForUser("alice") ``` ### Response #### Success Response (List) - **implicitRoles** (List) - A list of implicit roles the user possesses. ``` -------------------------------- ### EnforceEx (Python) Source: https://casbin.org/docs/management-api Explains enforcement by returning matched rules. Returns the success status and the explanation. ```python ok, reason = e.enforce_ex(request) ``` -------------------------------- ### Get All Subjects (Java) Source: https://casbin.org/docs/management-api Retrieves a list of all subjects present in the current policy. ```java List allSubjects = e.getAllSubjects(); ``` -------------------------------- ### Create Python Enforcer with Model Text and SQLAlchemyAdapter Source: https://casbin.org/docs/get-started Set up a Casbin Enforcer in Python using model text and a SQLAlchemy adapter for SQLite. This example demonstrates creating the model configuration and initializing the enforcer. ```python import casbin import casbin_sqlalchemy_adapter # Use SQLAlchemy Casbin adapter with SQLLite DB adapter = casbin_sqlalchemy_adapter.Adapter('sqlite:///test.db') # Create a config model policy with open("rbac_example_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 """) # Create enforcer from adapter and config policy e = casbin.Enforcer('rbac_example_model.conf', adapter) ``` -------------------------------- ### Get All Subjects (Rust) Source: https://casbin.org/docs/management-api Retrieves a list of all subjects present in the current policy. ```rust let all_subjects = e.get_all_subjects(); ``` -------------------------------- ### Get All Subjects (C#) Source: https://casbin.org/docs/management-api Retrieves a list of all subjects present in the current policy. ```csharp var allSubjects = e.GetAllSubjects(); ``` -------------------------------- ### Load Policy from an Adapter Source: https://casbin.org/docs/adapters Load policy rules from an existing adapter into memory. This is the first step when migrating policies. ```go e, _ := NewEnforcer(m, A) ``` -------------------------------- ### Build Java Casbin CLI with Maven Source: https://casbin.org/docs/command-line-tools Navigate to the cloned directory and build the casbin-java-cli using Maven. The JAR file will be created in the target directory. ```bash cd casbin-java-cli mvn clean install ``` -------------------------------- ### Get All Subjects (Python) Source: https://casbin.org/docs/management-api Retrieves a list of all subjects present in the current policy. ```python all_subjects = e.get_all_subjects() ``` -------------------------------- ### Get All Subjects (PHP) Source: https://casbin.org/docs/management-api Retrieves a list of all subjects present in the current policy. ```php $allSubjects = $e->getAllSubjects(); ```