概念

Casbin中最核心的三个概念:Model, Policy, Enforcer

Model就是一个CONF文件,基于PERM metamodel (Policy, Effect, Request, Matchers)。

Policy是动态存储policy rules的,可以存在.csv文件或数据库中。

Enforcer决定一个"subject"对一个"object"是否有"action"的权限。

安装

通过composer安装:

composer require casbin/casbin

使用

创建 model.confpolicy.csv 文件:

model.conf:

[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

policy.csv:

p, alice, data1, read
p, bob, data2, write

创建一个Casbin决策器需要有一个模型文件和策略文件为参数:

require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");

在需要进行访问控制的位置,通过以下代码进行权限验证:

$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) {
    // 允许 alice 读取 data1
} else {
    // 拒绝请求, 显示错误
}
Last Updated:
贡献者: Tinywan