Get Started
安装
go get github.com/casbin/casbin/v3
从 Casbin v2 升级到 v3 时,把导入路径从 github.com/casbin/casbin/v2 改成 github.com/casbin/casbin/v3。所有子包也一样(例如 v2/model 改为 v3/model)。
使用 Go modules 时,运行:
go get -u github.com/casbin/casbin/v3
然后把代码中所有的 /v2 导入改为 /v3。
对于Maven:
<!-- https://mvnrepository.com/artifact/org.casbin/jcasbin -->
<dependency>
<groupId>org.casbin</groupId>
<artifactId>jcasbin</artifactId>
<version>1.x.y</version>
</dependency>
GraalVM Native Image 支持
如果你用 GraalVM 构建原生应用(例如使用 Quarkus 或 Spring Native),由于 jCasbin 使用了 Aviator 表达式引擎,需要做特别的配置。
默认情况下,Aviator 通过 ASM 动态生成类,而 GraalVM native image 不支持这种方式。解决办法是把 Aviator 配置为解释模式,而不是编译模式。
Quarkus 应用
在 application.properties 或 pom.xml 中加入:
<properties>
<quarkus.native.additional-build-args>
-J-Daviator.eval.mode=INTERPRETER
</quarkus.native.additional-build-args>
</properties>
其他 GraalVM 原生构建
构建 native image 时设置系统属性:
-Daviator.eval.mode=INTERPRETER
或者在初始化 jCasbin 之前用代码配置:
System.setProperty("aviator.eval.mode", "INTERPRETER");
这个配置把 Aviator 从默认的编译模式切换到解释模式。这可能会稍微影响性能,但由于避免了运行时生成类,可以完全兼容 GraalVM native image。
# NPM
npm install casbin --save
# Yarn
yarn add casbin
在您的项目的composer.json中需要这个包以下载该包:
composer require casbin/casbin
pip install casbin
dotnet add package Casbin.NET
# Download source
git clone https://github.com/apache/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
cargo install cargo-edit
cargo add casbin
// If you use async-std as async executor
cargo add async-std
// If you use tokio as async executor, make sure you activate its `macros` feature
cargo add tokio
Casbin4D 已为 Delphi 10.3 Rio 打包,可以直接在 IDE 中安装。注意其中不包含可视化组件,这个库由一些独立的单元组成,需要单独导入到项目中。
luarocks install casbin
如果遇到错误 "Your user does not have write permissions in /usr/local/lib/luarocks/rocks",用管理员权限运行命令,或者加 --local 参数安装到本地目录:
luarocks install casbin --local
创建 Casbin Enforcer
Casbin 通过配置文件指定访问控制模型。
需要两个配置文件:model.conf 和 policy.csv。模型 文件定义访问控制模型;策略 文件保存权限规则。实际使用中你只和一个组件打交道,即 Enforcer,它在创建时加载这两个文件。
创建 Enforcer 需要提供一个 模型 和一个 适配器。
Casbin提供了一个您可以使用的文件适配器。查看适配器以获取更多信息。
- 使用模型文件和默认的 FileAdapter 的示例:
import "github.com/casbin/casbin/v3"
e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
import org.casbin.jcasbin.main.Enforcer;
Enforcer e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
import { newEnforcer } from 'casbin';
const e = await newEnforcer('path/to/model.conf', 'path/to/policy.csv');
require_once './vendor/autoload.php';
use Casbin\Enforcer;
$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
import casbin
e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv")
using NetCasbin;
var e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
#include <iostream>
#include <casbin/casbin.h>
int main() {
// Create an Enforcer
casbin::Enforcer e("path/to/model.conf", "path/to/policy.csv");
// your code ..
}
var
casbin: ICasbin;
begin
casbin := TCasbin.Create('path/to/model.conf', 'path/to/policy.csv');
...
end
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(())
}
local Enforcer = require("casbin")
local e = Enforcer:new("path/to/model.conf", "path/to/policy.csv") -- The Casbin Enforcer
- 使用模型文本和其他适配器的示例:
import (
"log"
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
xormadapter "github.com/casbin/xorm-adapter/v2"
_ "github.com/go-sql-driver/mysql"
)
// Initialize a Xorm adapter with MySQL database.
a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
if err != nil {
log.Fatalf("error: adapter: %s", err)
}
m, err := 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
`)
if err != nil {
log.Fatalf("error: model: %s", err)
}
e, err := casbin.NewEnforcer(m, a)
if err != nil {
log.Fatalf("error: enforcer: %s", err)
}
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)
检查权限
在代码中访问资源之前加上一次判定检查:
sub := "alice" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.
ok, err := e.Enforce(sub, obj, act)
if err != nil {
// handle err
}
if ok == true {
// permit alice to read data1
} else {
// deny the request, show an error
}
// You could use BatchEnforce() to enforce some requests in batches.
// This method returns a bool slice, and this slice's index corresponds to the row index of the two-dimensional array.
// e.g. results[0] is the result of {"alice", "data1", "read"}
results, err := e.BatchEnforce([][]interface{}{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"jack", "data3", "read"}})
String sub = "alice"; // the user that wants to access a resource.
String obj = "data1"; // the resource that is going to be accessed.
String act = "read"; // the operation that the user performs on the resource.
if (e.enforce(sub, obj, act) == true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
如果在 GraalVM native image 环境中运行 jCasbin,请确认已按上面安装一节所述把 Aviator 配置为解释模式。没有这个配置,会因为尝试在运行时生成类而遇到 UnsupportedFeatureError。
const sub = 'alice'; // the user that wants to access a resource.
const obj = 'data1'; // the resource that is going to be accessed.
const act = 'read'; // the operation that the user performs on the resource.
if ((await e.enforce(sub, obj, act)) === true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$act = "read"; // the operation that the user performs on the resource.
if ($e->enforce($sub, $obj, $act) === true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
sub = "alice" # the user that wants to access a resource.
obj = "data1" # the resource that is going to be accessed.
act = "read" # the operation that the user performs on the resource.
if e.enforce(sub, obj, act):
# permit alice to read data1
pass
else:
# deny the request, show an error
pass
var sub = "alice"; // the user that wants to access a resource.
var obj = "data1"; // the resource that is going to be accessed.
var act = "read"; // the operation that the user performs on the resource.
if (await e.EnforceAsync(sub, obj, act))
{
// permit alice to read data1
}
else
{
// deny the request, show an error
}
casbin::Enforcer e("../assets/model.conf", "../assets/policy.csv");
if (e.Enforce({"alice", "/alice_data/hello", "GET"})) {
std::cout << "Enforce OK" << std::endl;
} else {
std::cout << "Enforce NOT Good" << std::endl;
}
if (e.Enforce({"alice", "/alice_data/hello", "POST"})) {
std::cout << "Enforce OK" << std::endl;
} else {
std::cout << "Enforce NOT Good" << std::endl;
}
if casbin.enforce(['alice,data1,read']) then
// Alice is super happy as she can read data1
else
// Alice is sad
let sub = "alice"; // the user that wants to access a resource.
let obj = "data1"; // the resource that is going to be accessed.
let act = "read"; // the operation that the user performs on the resource.
if e.enforce((sub, obj, act)).await? {
// permit alice to read data1
} else {
// error occurs
}
if e:enforce("alice", "data1", "read") then
-- permit alice to read data1
else
-- deny the request, show an error
end
Casbin 提供在运行时管理权限的 API。例如,可以获取分配给某个用户的所有角色:
roles, err := e.GetRolesForUser("alice")
List<String> roles = e.getRolesForUser("alice");
const roles = await e.getRolesForUser('alice');
$roles = $e->getRolesForUser("alice");
roles = e.get_roles_for_user("alice")
var roles = e.GetRolesForUser("alice");
roles = e.rolesForEntity("alice")
let roles = e.get_roles_for_user("alice");
local roles = e:GetRolesForUser("alice")
更多示例见 Management API 和 RBAC API。也可以浏览各语言仓库中的测试用例。