快速上手
安装
go get github.com/casbin/casbin/v3
如果你要从 Casbin v2 升级到 v3,请把你的 import 路径从 github.com/casbin/casbin/v2 改为 github.com/casbin/casbin/v3。这一点同样适用于所有子包(例如 v2/model 要改为 v3/model)。
对于 Go modules,请执行:
go get -u github.com/casbin/casbin/v3
然后把你代码中所有的 import 从 /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 原生镜像不支持这一点。要解决该问题,你必须把 Aviator 配置为使用解释器模式,而不是编译模式。
对于 Quarkus 应用
在你的 application.properties 或 pom.xml 中添加以下内容:
<properties>
<quarkus.native.additional-build-args>
-J-Daviator.eval.mode=INTERPRETER
</quarkus.native.additional-build-args>
</properties>
对于其他 GraalVM 原生构建
在构建原生镜像时设置该系统属性:
-Daviator.eval.mode=INTERPRETER
或者在初始化 jCasbin 之前通过代码进行配置:
System.setProperty("aviator.eval.mode", "INTERPRETER");
该配置会把 Aviator 从默认的编译模式切换为解释器模式。虽然这可能会对性能有轻微影响,但它避免了运行时的类生成,从而完全兼容 GraalVM 原生镜像。
# 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,需要提供一个 Model 和一个 Adapter。
Casbin 提供了一个你可以直接使用的 FileAdapter。更多信息请参见 Adapter。
- 使用 Model 文件和默认的 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
- 使用 Model 文本和其他 Adapter 的示例:
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 原生镜像环境中运行 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")