PHP-Casbin 是一个强大的、高效的开源访问控制框架,它支持基于各种访问控制模型(RBAC ABAC ACL)的权限管理。

这里使用官方提供的数据库适配器扩展:Database adapter.

安装

通过composer安装:

composer require casbin/casbin

composer require casbin/dbal-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\DBAL\Adapter;

$adapter = Adapter::newAdapter([

'driver' => 'pdo_mysql',

'host' => '127.0.0.1',

'dbname' => 'test',

'user' => 'root',

'password' => '',

'port' => '3306',

]);

$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

本作品采用《CC 协议》,转载必须注明作者和本文链接

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐