PHP-Casbin 是一個強大的、高效的開源訪問控制框架,它支援基於各種訪問控制模型(RBAC
ABAC
ACL
)的許可權管理。
這裡使用官方提供的資料庫介面卡擴充套件:Database adapter.
安裝
通過composer
安裝:
composer require casbin/casbin
composer require casbin/database-adapter
使用 RBAC Model
model.conf 如下:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
# RBAC角色繼承關係的定義
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)
初始化一個Casbin enforcer
use Casbin\Enforcer;
use CasbinAdapter\Database\Adapter;
$adapter = Adapter::newAdapter([
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'test',
'username' => 'root',
]);
$enforcer = new Enforcer('path/to/model.conf', $adapter);
新增策略
給alice和bob分配角色:
// alice has the admin role
$enforcer->addRoleForUser('alice', 'admin');
// bob has the member role
$enforcer->addRoleForUser('bob', 'member');
給member角色分配許可權,member
角色僅對foo
資源有檢視許可權:
$enforcer->addPermissionForUser('member', '/foo', 'GET');
$enforcer->addPermissionForUser('member', '/foo/:id', 'GET');
admin
角色對foo
擁有增刪改查許可權:
// admin inherits all permissions of member
$enforcer->addRoleForUser('admin', 'member');
$enforcer->addPermissionForUser('admin', '/foo', 'POST');
$enforcer->addPermissionForUser('admin', '/foo/:id', 'PUT');
$enforcer->addPermissionForUser('admin', '/foo/:id', 'DELETE');
分配完角色和許可權後,資料庫中的策略規則大致如下:
g, alice, admin
g, bob, member
p, memeber, /foo, GET
p, memeber, /foo/:id, GET
g, admin, member
p, admin, /foo, POST
p, admin, /foo/:id, PUT
p, admin, /foo/:id, DELETE
驗證許可權
alice
具有admin
角色,繼承admin
和member
兩個角色的全部許可權.
$enforcer->enforce('alice', '/foo', 'GET'); // true
$enforcer->enforce('alice', '/foo', 'GET'); // true
$enforcer->enforce('alice', '/foo', 'POST'); // true
$enforcer->enforce('alice', '/foo/1', 'PUT'); // true
$enforcer->enforce('alice', '/foo/1', 'DELETE'); // true
bob
具有member
角色, 只繼承member
的許可權.
$enforcer->enforce('bob', '/foo', 'GET'); // true
$enforcer->enforce('bob', '/foo', 'GET'); // true
$enforcer->enforce('bob', '/foo', 'POST'); // false
$enforcer->enforce('bob', '/foo/1', 'PUT'); // false
$enforcer->enforce('bob', '/foo/1', 'DELETE'); // false