### Install Dependencies and Start Local Development Source: https://github.com/apache/casbin-website/blob/master/README.md Clone the repository, install dependencies using Yarn, and start the local development server. ```bash git clone https://github.com/apache/casbin-website.git cd casbin-website yarn install yarn start ``` -------------------------------- ### Install Casbin for Go Source: https://context7.com/apache/casbin-website/llms.txt Use 'go get' to install the Casbin library for Go projects. ```bash # Go go get github.com/casbin/casbin/v3 ``` -------------------------------- ### Install Casbin for Go Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Use 'go get' to install the Casbin library for Go projects. For upgrading from v2 to v3, update import paths and run 'go get -u'. ```bash go get github.com/casbin/casbin/v3 ``` ```bash go get -u github.com/casbin/casbin/v3 ``` -------------------------------- ### KeyGet Example (Two-Parameter) Source: https://github.com/apache/casbin-website/blob/master/docs/Function.mdx Example demonstrating the two-parameter form of the KeyGet function. ```go KeyGet("/resource1/action", "/*") → "resource1/action" ``` -------------------------------- ### Cloud Provider Middleware - Okta Source: https://github.com/apache/casbin-website/blob/master/docs/Middlewares.mdx Integration example for Okta with Casbin, referencing a demo project for setup. ```Markdown [Okta](https://okta.com/) | One trusted platform to secure every identity, via plugin: [casbin-spring-boot-demo](https://github.com/myriad-personal/casbin-spring-boot-demo) ``` -------------------------------- ### Cloud Provider Middleware - Auth0 Source: https://github.com/apache/casbin-website/blob/master/docs/Middlewares.mdx Integration example for Auth0 with Casbin, referencing a plugin for setup. ```Markdown [Auth0](https://auth0.com/) | An easy to implement, adaptable authentication and authorization platform, via plugin: [casbin-auth0-rbac](https://auth0.com/) ``` -------------------------------- ### KeyGet2 Example Source: https://github.com/apache/casbin-website/blob/master/docs/Function.mdx Example demonstrating the KeyGet2 function for extracting a resource name. ```go KeyGet2("/resource1/action", "/:res/action", "res") → "resource1" ``` -------------------------------- ### KeyGet3 Example Source: https://github.com/apache/casbin-website/blob/master/docs/Function.mdx Example demonstrating the KeyGet3 function for extracting a resource name with a different pattern. ```go KeyGet3("/resource1_admin/action", "/{res}_admin/*", "res") → "resource1" ``` -------------------------------- ### Test Authorization Request Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Sends a GET request to the root path of the example service, specifying 'example.com' as the host and 'anonymous' as the user. This tests the configured authorization rules. ```bash curl -i -X GET \ --url http://localhost:8000/ \ --header 'Host: example.com' \ --header 'user: anonymous' ``` -------------------------------- ### Install Kong-Authz Plugin Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Installs the kong-authz plugin from its rockspec file. ```bash sudo luarocks install https://raw.githubusercontent.com/casbin-lua/kong-authz/master/kong-authz-0.0.1-1.rockspec ``` -------------------------------- ### Create Example Service in Kong Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Creates a new example service named 'example-service' pointing to the 'http://mockbin.org' URL. ```bash curl -i -X POST \ --url http://localhost:8001/services/ \ --data 'name=example-service' \ --data 'url=http://mockbin.org' ``` -------------------------------- ### Install casbin-ucon Extension Source: https://github.com/apache/casbin-website/blob/master/docs/UCON.mdx Use this command to install the casbin-ucon extension library for Go projects. ```bash go get github.com/casbin/casbin-ucon ``` -------------------------------- ### Create Route for Example Service Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Creates a route for the 'example-service' that listens on the 'example.com' host. ```bash curl -i -X POST \ --url http://localhost:8001/services/example-service/routes \ --data 'hosts[]=example.com' ``` -------------------------------- ### Install Casbin.js with yarn Source: https://github.com/apache/casbin-website/blob/master/docs/FrontendUsage.mdx Install the casbin.js package using yarn. ```bash yarn add casbin.js ``` -------------------------------- ### Basic Policy Example Source: https://context7.com/apache/casbin-website/llms.txt Example of a basic policy file defining user permissions and role assignments. ```csv # basic_policy.csv p, alice, data1, read p, bob, data2, write g, alice, admin ``` -------------------------------- ### Install Casbin.js with npm Source: https://github.com/apache/casbin-website/blob/master/docs/FrontendUsage.mdx Install the casbin.js package and the core casbin package using npm. ```bash npm install casbin.js npm install casbin ``` -------------------------------- ### Install Rust Casbin CLI from crates.io Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Install the casbin-rust-cli directly from crates.io using cargo. ```bash cargo install casbin-rust-cli ``` -------------------------------- ### Install Casbin for Python Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Install the Casbin library for Python using pip. ```bash pip install casbin ``` -------------------------------- ### Update Policy Examples in Go Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Demonstrates how to use UpdatePolicy, UpdatePolicies, and UpdateFilteredPolicies with a Casbin enforcer and a GORM adapter. ```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", ) ``` -------------------------------- ### Apply Envoy Configuration Source: https://github.com/apache/casbin-website/blob/master/docs/EnvoyAuthz.mdx Starts Envoy with the specified configuration file to enable the authorization middleware. ```bash envoy -c authz.yaml -l info ``` -------------------------------- ### Clone Go Casbin CLI Repository Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Clone the casbin-go-cli repository to get started with the Go implementation. ```bash git clone https://github.com/casbin/casbin-go-cli.git ``` -------------------------------- ### Clone .NET Casbin CLI Repository Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Clone the casbin-dotnet-cli repository to get started with the .NET implementation. ```bash git clone https://github.com/casbin-net/casbin-dotnet-cli.git ``` -------------------------------- ### Install Casbin for Node.js Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Install the Casbin package for Node.js using either NPM or Yarn. ```bash # NPM npm install casbin --save # Yarn yarn add casbin ``` -------------------------------- ### Install Casbin for Lua Source: https://context7.com/apache/casbin-website/llms.txt Use luarocks to install the Casbin library for Lua. ```bash # Lua luarocks install casbin ``` -------------------------------- ### Install Casbin for .NET Source: https://context7.com/apache/casbin-website/llms.txt Use the dotnet CLI to add the Casbin.NET package to your project. ```bash # .NET dotnet add package Casbin.NET ``` -------------------------------- ### EnforceEx() - Get Policy Rules and Decision Source: https://context7.com/apache/casbin-website/llms.txt Use EnforceEx to get the decision, matching policy rules, and any associated reason. Useful for debugging and audit logging. ```Go // Go ok, reason, err := e.EnforceEx("alice", "data1", "read") // reason = [["alice", "data1", "read"]] — the matching policy rule(s) fmt.Printf("allowed=%v reason=%v\n", ok, reason) ``` ```javascript // Node.js const [ok, reason] = await e.enforceEx('alice', 'data1', 'read'); ``` ```python # Python ok, reason = e.enforce_ex("alice", "data1", "read") ``` ```csharp // .NET (async) var (ok, explain) = await e.EnforceExAsync("alice", "data1", "read"); ``` -------------------------------- ### Casbin Policy Example Source: https://github.com/apache/casbin-website/blob/master/docs/CasbinRBACAndRBAC96.mdx This example demonstrates a typical Casbin policy in CSV format, showing how users, roles, and permissions are defined. It illustrates Casbin's flexible approach where users and roles are treated as strings. ```csv p, admin, book, read p, alice, book, read g, amber, admin ``` -------------------------------- ### Install Python Casbin CLI Dependencies Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Install the required dependencies for the casbin-python-cli after cloning the repository. ```bash cd casbin-python-cli pip install -r requirements.txt ``` -------------------------------- ### Example Policy (CSV) Source: https://github.com/apache/casbin-website/blob/master/docs/PolicyStorage.mdx This is an example of a policy stored in CSV format, which can be used as a basis for database storage. ```csv p, data2_admin, data2, read p, data2_admin, data2, write g, alice, admin ``` -------------------------------- ### Kubernetes Deployment YAML Example Source: https://github.com/apache/casbin-website/blob/master/docs/K8sGateKeeper.mdx An example of a Kubernetes Deployment manifest for an Nginx pod. This is used to illustrate how an admission request is formed. ```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 ``` -------------------------------- ### Install Casbin System Dependencies (apt) Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Installs necessary system dependencies for Casbin on Debian-based systems using apt. ```bash sudo apt install gcc libpcre3 libpcre3-dev ``` -------------------------------- ### Install Casbin System Dependencies (Alpine) Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Installs necessary system dependencies for Casbin on Alpine-based systems using apk. ```bash sudo apk add gcc pcre pcre-dev libc-dev ``` -------------------------------- ### User-Role Mapping Example Source: https://github.com/apache/casbin-website/blob/master/docs/RBAC.mdx Example of how user-role mappings are stored in the policy. `alice` is assigned the `data2_admin` role. ```csv p, data2_admin, data2, read g, alice, data2_admin ``` -------------------------------- ### Casbin Default Logger Example Source: https://github.com/apache/casbin-website/blob/master/docs/LogError.mdx This is an example of the output format from Casbin's default logger when logging requests. Ensure logging is enabled to see such output. ```log 2017/07/15 19:43:56 [Request: alice, data1, read ---> true] ``` -------------------------------- ### Install K8s-gatekeeper via Helm Source: https://github.com/apache/casbin-website/blob/master/docs/K8sGateKeeper.mdx Installs K8s-gatekeeper using Helm. Assumes the Helm chart is available at './k8sgatekeeper'. ```shell helm install k8sgatekeeper ./k8sgatekeeper ``` -------------------------------- ### RBAC Model Configuration Source: https://context7.com/apache/casbin-website/llms.txt Example configuration for Role-Based Access Control (RBAC) using [role_definition] and the g() function. Includes model and policy file examples. ```ini # rbac_model.conf [request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act ``` ```csv # rbac_policy.csv p, data2_admin, data2, read p, data2_admin, data2, write g, alice, data2_admin ``` ```Go // Go — alice inherits data2_admin's permissions ok, _ := e.Enforce("alice", "data2", "read") // true ``` -------------------------------- ### Filtered API Examples Source: https://github.com/apache/casbin-website/blob/master/docs/ManagementAPI.mdx Examples demonstrating how to use the Filtered API with different field indices and values to retrieve specific policy rules. ```APIDOC ## Filtered API Filtered methods take `(fieldIndex int, fieldValues ...string)`: matching starts at `fieldIndex`, and `fieldValues` are the required values at consecutive positions. Use `""` in `fieldValues` as a wildcard for that position. ### Example Usage ```go // Assuming 'e' is an Enforcer instance and a CSV policy is loaded. // Get all policies related to "book" e.GetFilteredPolicy(1, "book") // returns: [["alice", "book", "read"], ["bob", "book", "read"], ["bob", "book", "write"]] // Get all policies related to "book" with "read" action e.GetFilteredPolicy(1, "book", "read") // returns: [["alice", "book", "read"], ["bob", "book", "read"]] // Get all policies for "alice" with "read" action, allowing any object e.GetFilteredPolicy(0, "alice", "", "read") // returns: [[alice book read]] // Get all policies for "alice" e.GetFilteredPolicy(0, "alice") // returns: [["alice", "book", "read"], ["alice", "pen", "get"]] ``` ``` -------------------------------- ### Install Casbin for Lua Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Install the Casbin Lua rock using luarocks. If you lack write permissions, use the '--local' flag. ```bash luarocks install casbin ``` ```bash luarocks install casbin --local ``` -------------------------------- ### RBAC with Conditions Policy Example Source: https://github.com/apache/casbin-website/blob/master/docs/RBACWithConditions.mdx Example policy rules for RBAC with conditions. The `g` rules include start and end times as extra arguments for condition functions, with `_` indicating ignored parameters. ```csv 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, _ ``` -------------------------------- ### Basic Matcher Syntax Source: https://github.com/apache/casbin-website/blob/master/docs/SyntaxForModels.mdx Defines how requests are evaluated against policy rules. This example requires exact matches for subject, object, and action. ```ini [matchers] m = r.sub == p.sub && r.obj == p.obj && r.act == p.act ``` -------------------------------- ### Clone Python Casbin CLI Repository Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Clone the casbin-python-cli repository to get started with the Python implementation. ```bash git clone https://github.com/casbin/casbin-python-cli.git ``` -------------------------------- ### Initialize Enforcer with File Adapter Instance (Go) Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initialize an enforcer by first creating a file adapter instance with the policy file path, 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) ``` -------------------------------- ### Clone Java Casbin CLI Repository Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Clone the casbin-java-cli repository to get started with the Java implementation. ```bash git clone https://github.com/jcasbin/casbin-java-cli.git ``` -------------------------------- ### Build Casbin for C++ Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Clone the Casbin C++ repository, generate build files with CMake, and then build and install 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 ``` -------------------------------- ### Example ACL Policy Source: https://github.com/apache/casbin-website/blob/master/docs/HowItWorks.mdx Sample policy entries for the minimal ACL model, defining specific user-resource-action permissions. ```csv p, alice, data1, read p, bob, data2, write ``` -------------------------------- ### Policy Rule Example Source: https://github.com/apache/casbin-website/blob/master/docs/SyntaxForModels.mdx Illustrates the format of policy rules in a CSV file, where the first token is the policy type matching a definition. ```csv p, alice, data1, read p2, bob, write-all-objects ``` -------------------------------- ### Implement UCON with casbin-ucon in Go Source: https://github.com/apache/casbin-website/blob/master/docs/UCON.mdx Demonstrates how to initialize a Casbin enforcer, wrap it with casbin-ucon, add conditions and obligations, create a session, and enforce policies within that session. Includes session monitoring and attribute updates. ```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 monitoring when done _ = uconE.StopMonitoring(sessionID) } ``` -------------------------------- ### Custom TimeMatch Condition Function Implementation Source: https://github.com/apache/casbin-website/blob/master/docs/RBACWithConditions.mdx Provides an example implementation of a custom condition function `TimeMatchFunc` and its underlying logic `TimeMatch`. `TimeMatch` checks if the current time falls within a specified start and end time, supporting `_` for ignored parameters. ```go // TimeMatchFunc is the wrapper for TimeMatch. func TimeMatchFunc(args ...string) (bool, error) { if err := validateVariadicStringArgs(2, args...); err != nil { return false, fmt.Errorf("%s: %s", "TimeMatch", err) } return TimeMatch(args[0], args[1]) } // TimeMatch determines whether the current time is between startTime and endTime. // You can use "_" to indicate that the parameter is ignored func TimeMatch(startTime, endTime string) (bool, error) { now := time.Now() if startTime != "_" { if start, err := time.Parse("2006-01-02 15:04:05", startTime); err != nil { return false, err } else if !now.After(start) { return false, nil } } if endTime != "_" { if end, err := time.Parse("2006-01-02 15:04:05", endTime); err != nil { return false, err } else if !now.Before(end) { return false, nil } } return true, nil } ``` -------------------------------- ### Initialize Enforcer with File Adapter Instance (PHP) Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initialize an enforcer by first creating a file adapter instance with the policy file path, 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); ``` -------------------------------- ### Prepare and Run External Webhook Source: https://github.com/apache/casbin-website/blob/master/docs/K8sGateKeeper.mdx Prepares the Go modules and runs the external webhook. Ensure your hosts file is updated for 'webhook.domain.local' and apply CRDs and external webhook configuration. ```shell go mod tidy go mod vendor go run cmd/webhook/main.go kubectl apply -f config/auth.casbin.org_casbinmodels.yaml kubectl apply -f config/auth.casbin.org_casbinpolicies.yaml kubectl apply -f config/webhook_external.yaml ``` -------------------------------- ### Backend Endpoint for Permissions Source: https://github.com/apache/casbin-website/blob/master/docs/FrontendUsage.mdx Example of a backend endpoint (using Beego framework in Go) that exposes user permissions to the frontend using `CasbinJsGetPermissionForUser`. ```APIDOC ## Backend Integration On the backend, expose an endpoint (such as a REST API) that generates the permission object for the frontend. In your API controller, call `CasbinJsGetUserPermission` to construct the permission object. This Beego example demonstrates the pattern: :::note Your endpoint should return a response like: ```json { "other":"other", "data": "What you get from `CasbinJsGetPermissionForUser`" } ``` ::: ```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() } ``` :::note Currently, `CasbinJsGetPermissionForUser` is available only in Go Casbin and Node-Casbin. To request support in other languages, please [open an issue](https://github.com/casbin/casbin.js/issues) or leave a comment below. ::: ``` -------------------------------- ### Migrate Policies Between Adapters Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Demonstrates the process of migrating policies from one adapter to another. This involves loading policies from the source adapter, switching to the target adapter, and saving the policies. ```go e, _ := NewEnforcer(m, A) e.SetAdapter(A) e.LoadPolicy() ``` ```go e.SetAdapter(B) ``` ```go e.SavePolicy() ``` -------------------------------- ### Install Casbin Lua Module Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Installs the latest Casbin release for Lua from LuaRocks. ```bash sudo luarocks install casbin ``` -------------------------------- ### Initialize Enforcer with File Adapter (Go) Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initialize an enforcer using the built-in file adapter by providing the model configuration and policy file paths directly. ```go import "github.com/casbin/casbin/v3" e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") ``` -------------------------------- ### Add, Remove, Update, and Check Policies in Go Source: https://github.com/apache/casbin-website/blob/master/docs/APIOverview.mdx Demonstrates how to modify and verify individual policies at runtime using AddPolicy, RemovePolicy, UpdatePolicy, and HasPolicy. Ensure the enforcer is initialized with your model and policy files. ```go enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv") if err != nil { fmt.Printf("Error, details: %s\n", err) } enforcer.AddPolicy("added_user", "data1", "read") hasPolicy := enforcer.HasPolicy("added_user", "data1", "read") fmt.Println(hasPolicy) // true, the policy was added successfully enforcer.RemovePolicy("alice", "data1", "read") hasPolicy = enforcer.HasPolicy("alice", "data1", "read") fmt.Println(hasPolicy) // false, the policy was removed successfully enforcer.UpdatePolicy([]string{"added_user", "data1", "read"}, []string{"added_user", "data1", "write"}) hasPolicy = enforcer.HasPolicy("added_user", "data1", "read") fmt.Println(hasPolicy) // false, the original policy has expired hasPolicy = enforcer.HasPolicy("added_user", "data1", "write") fmt.Println(hasPolicy) // true, the new policy is in effect ``` -------------------------------- ### Apply Kong-Authz Plugin to Service Source: https://github.com/apache/casbin-website/blob/master/docs/KongAuthz.mdx Applies the kong-authz plugin to the 'example-service', specifying the model and policy file paths and the username header. ```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' ``` -------------------------------- ### Initialize Casbin Enforcer with MySQL Adapter in Go Source: https://context7.com/apache/casbin-website/llms.txt Connect to a MySQL database to load and persist policies. Provide the correct DSN. ```go // MySQL adapter import mysqladapter "github.com/casbin/mysql-adapter" a, _ = mysqladapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/") e, _ = casbin.NewEnforcer("model.conf", a) ``` -------------------------------- ### Initialize Custom Storage Adapter Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initializes a Casbin enforcer with a custom storage adapter. Replace `yourpackage` and `params` with your specific implementation details. ```go import ( "github.com/casbin/casbin/v3" "github.com/your-username/your-repo" ) a := yourpackage.NewAdapter(params) e := casbin.NewEnforcer("examples/basic_model.conf", a) ``` -------------------------------- ### BLP Model Request Examples Source: https://github.com/apache/casbin-website/blob/master/docs/BLP.mdx Illustrates various read and write operations with different subject and object security levels, demonstrating allowed and denied access according to BLP rules. ```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) ``` -------------------------------- ### Get All Roles Source: https://github.com/apache/casbin-website/blob/master/docs/ManagementAPI.mdx Retrieves all roles present in the current policy. Use this to get a comprehensive list of defined roles. ```Go allRoles = e.GetAllRoles() ``` ```Node.js const allRoles = await e.getAllRoles() ``` ```PHP $allRoles = $e->getAllRoles(); ``` ```Python all_roles = e.get_all_roles() ``` ```C# var allRoles = e.GetAllRoles(); ``` ```Rust let all_roles = e.get_all_roles(); ``` ```Java List allRoles = e.getAllRoles(); ``` -------------------------------- ### Get All Objects Source: https://github.com/apache/casbin-website/blob/master/docs/ManagementAPI.mdx Retrieves all unique objects present in the current policy. Use this to get a list of all resources being managed. ```go allObjects := e.GetAllObjects() ``` ```typescript 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(); ``` -------------------------------- ### LBAC Example Requests Source: https://github.com/apache/casbin-website/blob/master/docs/LBAC.mdx Demonstrates various read and write operations with different subject and object security levels, illustrating allowed and denied scenarios based on the LBAC model's rules. ```text # 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) ``` -------------------------------- ### Initialize MySQL Adapter in Go Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initializes a Casbin enforcer using the MySQL adapter. Ensure the MySQL server is accessible and the database/tables are set up. ```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) ``` -------------------------------- ### Casbin UCON Policy Example Source: https://github.com/apache/casbin-website/blob/master/docs/UCON.mdx A basic policy example for Casbin. In UCON, conditions and obligations are managed in code, not in the policy file. ```csv p, alice, document1, read ``` -------------------------------- ### Build Rust Casbin CLI from Source Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Build the casbin-rust-cli with release optimizations after cloning the repository. ```bash cd casbin-rust-cli cargo build --release ``` -------------------------------- ### Initialize Enforcer with File Adapter Instance (Rust) Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initialize an enforcer by first creating a file adapter instance with the policy file path, then passing it to the enforcer. ```rust use casbin::prelude::*; let a = FileAdapter::new("examples/basic_policy.csv"); let e = Enforcer::new("examples/basic_model.conf", a).await?; ``` -------------------------------- ### Build .NET Casbin CLI Project Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Build the casbin-dotnet-cli project after cloning the repository. ```bash cd casbin-dotnet-cli dotnet build ``` -------------------------------- ### Get All Named Actions Source: https://github.com/apache/casbin-website/blob/master/docs/ManagementAPI.mdx Retrieves all unique actions from a specific named policy. Provide the policy name to get actions associated with that policy. ```go allNamedActions := e.GetAllNamedActions("p") ``` ```typescript const allNamedActions = await e.getAllNamedActions('p') ``` ```php $allNamedActions = $e->getAllNamedActions("p"); ``` ```python all_named_actions = e.get_all_named_actions("p") ``` ```csharp var allNamedActions = e.GetAllNamedActions("p"); ``` ```rust let all_named_actions = e.get_all_named_actions("p"); ``` ```java List allNamedActions = e.getAllNamedActions("p"); ``` -------------------------------- ### Initialize Enforcer with File Adapter (PHP) Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Initialize an enforcer using the built-in file adapter by providing the model configuration and policy file paths directly. ```php use Casbin\Enforcer; $e = new Enforcer('examples/basic_model.conf', 'examples/basic_policy.csv'); ``` -------------------------------- ### Build Go Casbin CLI Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Build the casbin-go-cli executable after cloning the repository. ```bash cd casbin-go-cli go build -o casbin ``` -------------------------------- ### Launch Envoy Authorization Server Source: https://github.com/apache/casbin-website/blob/master/docs/EnvoyAuthz.mdx Builds and launches the envoy-authz service. Ensure Casbin policies are configured beforehand. ```bash go build . ./authz ``` -------------------------------- ### Create Casbin Enforcer with File Paths Source: https://github.com/apache/casbin-website/blob/master/docs/GetStarted.mdx Use this when initializing an Enforcer with separate model and policy configuration files. Ensure the file paths are correct. ```Go import "github.com/casbin/casbin/v3" e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv") ``` ```Java import org.casbin.jcasbin.main.Enforcer; Enforcer e = new Enforcer("path/to/model.conf", "path/to/policy.csv"); ``` ```Node.js import { newEnforcer } from 'casbin'; const e = await newEnforcer('path/to/model.conf', 'path/to/policy.csv'); ``` ```PHP require_once './vendor/autoload.php'; use Casbin\Enforcer; $e = new Enforcer("path/to/model.conf", "path/to/policy.csv"); ``` ```Python import casbin e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv") ``` ```C# using NetCasbin; var e = new Enforcer("path/to/model.conf", "path/to/policy.csv"); ``` ```C++ #include #include int main() { // Create an Enforcer casbin::Enforcer e("path/to/model.conf", "path/to/policy.csv"); // your code .. } ``` ```Delphi var casbin: ICasbin; begin casbin := TCasbin.Create('path/to/model.conf', 'path/to/policy.csv'); ... end ``` ```Rust use casbin::prelude::*; // If you use async_td as async executor #[cfg(feature = "runtime-async-std")] #[async_std::main] async fn main() -> Result<()> { let mut e = Enforcer::new("path/to/model.conf", "path/to/policy.csv").await?; Ok(()) } // If you use tokio as async executor #[cfg(feature = "runtime-tokio")] #[tokio::main] async fn main() -> Result<()> { let mut e = Enforcer::new("path/to/model.conf", "path/to/policy.csv").await?; Ok(()) } ``` ```Lua local Enforcer = require("casbin") local e = Enforcer:new("path/to/model.conf", "path/to/policy.csv") -- The Casbin Enforcer ``` -------------------------------- ### Using ContextAdapter with Timeout in Go Source: https://github.com/apache/casbin-website/blob/master/docs/Adapters.mdx Demonstrates how to use a ContextAdapter with a timeout. Ensure your adapter implements the ContextAdapter interface and supports context propagation for operations like AddPolicyCtx. ```go ca, _ := NewContextAdapter("mysql", "root:@tcp(127.0.0.1:3306)/", "casbin") // Set 300s timeout ctx, cancel := context.WithTimeout(context.Background(), 300*time.Microsecond) deferr cancel() err := ca.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"}) if err != nil { panic(err) } ``` -------------------------------- ### RBAC with Domains and Conditions Policy Example Source: https://github.com/apache/casbin-website/blob/master/docs/RBACWithConditions.mdx Policy rules for RBAC with domains and conditions. The `g` rules now include a domain and time-based condition arguments, similar to the non-domain example. ```csv p, alice, domain1, data1, read p, data2_admin, domain2, data2, write p, data3_admin, domain3, data3, read p, data4_admin, domain4, data4, write p, data5_admin, domain5, data5, read p, data6_admin, domain6, data6, write p, data7_admin, domain7, data7, read p, data8_admin, domain8, data8, write g, alice, data2_admin, domain2, 0000-01-01 00:00:00, 0000-01-02 00:00:00 g, alice, data3_admin, domain3, 0000-01-01 00:00:00, 9999-12-30 00:00:00 g, alice, data4_admin, domain4, _, _ g, alice, data5_admin, domain5, _, 9999-12-30 00:00:00 g, alice, data6_admin, domain6, _, 0000-01-02 00:00:00 g, alice, data7_admin, domain7, 0000-01-01 00:00:00, _ g, alice, data8_admin, domain8, 9999-12-30 00:00:00, _ ``` -------------------------------- ### Initialize Enforcer for RBAC Source: https://github.com/apache/casbin-website/blob/master/docs/RBACAPI.mdx Instantiate an Enforcer with RBAC model and policy files. Available for multiple languages. ```go e, err := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") ``` ```typescript 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"); ``` -------------------------------- ### ReBAC Policy and Relationship Examples Source: https://github.com/apache/casbin-website/blob/master/docs/ReBAC.mdx Provides concrete examples of ReBAC policies and relationships in Casbin's CSV format. This includes defining permissions based on roles and types, and establishing user-resource-role and resource-type mappings. ```csv # 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 ``` -------------------------------- ### ACL Policy and Request Example Source: https://github.com/apache/casbin-website/blob/master/blog/2023-12-08-understanding-casbin-matching-in-detail.md Provides sample policy rules and a request to test with the minimal ACL model. Demonstrates how to grant and check specific permissions. ```csv p, alice, read, data1 p, bob, write, data2 ``` ```csv alice, read, data1 ``` -------------------------------- ### Example Usage of Multiple Sections (Go) Source: https://github.com/apache/casbin-website/blob/master/docs/SyntaxForModels.mdx Pass a custom EnforceContext to enforce calls to use specific policy/request/effect/matcher definitions. You can also override individual types. ```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 ``` -------------------------------- ### Get All Permissions for User (Java) Source: https://github.com/apache/casbin-website/blob/master/docs/RBACAPI.mdx Retrieves all permissions for a user. ```java List> permissions = e.getPermissionsForUser("bob"); ``` -------------------------------- ### Creating an Enforcer Source: https://context7.com/apache/casbin-website/llms.txt Demonstrates how to create an Enforcer instance, which is the main entry point for Casbin's authorization logic. It can be initialized with model and policy files or configurations. ```APIDOC ## Creating an Enforcer The `Enforcer` is the main entry point. Provide a model path/string and a policy path/adapter. ```go // Go — file-based import "github.com/casbin/casbin/v3" e, err := casbin.NewEnforcer("model.conf", "policy.csv") if err != nil { log.Fatal(err) } ``` ```go // Go — inline model + database adapter (MySQL via Xorm) import ( "github.com/casbin/casbin/v3" "github.com/casbin/casbin/v3/model" xormadapter "github.com/casbin/xorm-adapter/v2" _ "github.com/go-sql-driver/mysql" ) a, _ := xormadapter.NewAdapter("mysql", "root:password@tcp(127.0.0.1:3306)/") m, _ := model.NewModelFromString(` [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 `) e, err := casbin.NewEnforcer(m, a) ``` ```javascript // Node.js import { newEnforcer } from 'casbin'; const e = await newEnforcer('model.conf', 'policy.csv'); ``` ```python # Python import casbin e = casbin.Enforcer("model.conf", "policy.csv") ``` ```java // Java import org.casbin.jcasbin.main.Enforcer; Enforcer e = new Enforcer("model.conf", "policy.csv"); ``` ```csharp // .NET using NetCasbin; var e = new Enforcer("model.conf", "policy.csv"); ``` ``` -------------------------------- ### Get All Permissions for User (.NET) Source: https://github.com/apache/casbin-website/blob/master/docs/RBACAPI.mdx Retrieves all permissions for a user. ```csharp var permissions = e.GetPermissionsForUser("bob"); ``` -------------------------------- ### Enforce and Explain Access Permission Source: https://github.com/apache/casbin-website/blob/master/docs/CommandLineTools.mdx Evaluate access permissions and display the matched policy using the enforceEx command. ```shell ./casbin enforceEx -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data2" "write" ``` -------------------------------- ### Get All Permissions for User (Python) Source: https://github.com/apache/casbin-website/blob/master/docs/RBACAPI.mdx Retrieves all permissions for a user. ```python e.get_permissions_for_user("bob") ``` -------------------------------- ### Get All Permissions for User (PHP) Source: https://github.com/apache/casbin-website/blob/master/docs/RBACAPI.mdx Retrieves all permissions for a user. ```php $e->getPermissionsForUser("bob"); ```