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.conf` 和 `policy.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决策器需要有一个模型文件和策略文件为参数:
```php
require_once './vendor/autoload.php';
use Casbin\Enforcer;
$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
```
在需要进行访问控制的位置,通过以下代码进行权限验证:
```php
$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 {
// 拒绝请求, 显示错误
}
```