PHP 中基於 Casbin 作 RBAC + RESTful 權限控制

PHP-Casbin 是一個強大的、高效的開源訪問控制框架,它支持基於各類訪問控制模型(RBAC ABAC ACL)的權限管理。php

這裏使用官方提供的數據庫適配器擴展:DBAL Adapter.html

安裝

經過composer安裝:mysql

composer require casbin/casbin
composer require casbin/dbal-adapter

使用 RBAC Model

model.conf 以下:git

[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分配角色:github

// alice has the admin role
$enforcer->addRoleForUser('alice', 'admin'); 
// bob has the member role
$enforcer->addRoleForUser('bob', 'member');

給member角色分配權限,member 角色僅對foo資源有查看權限:sql

$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');

分配完角色和權限後,數據庫中的策略規則大體以下:composer

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角色,繼承adminmember兩個角色的所有權限.框架

$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的權限.ui

$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

文章轉發原始連接:https://www.tech1024.com/collect/5/3016.html.

相關文章
相關標籤/搜索