Yii 內建 CAuthManager 實現了分層 RBAC(Role-Based Access Control),但缺乏視覺化管理介面。Srbac 是社群最成熟的 RBAC 管理模組,提供角色、任務、操作的圖形化增刪改查與指派。本文從核心概念、資料庫結構、安裝配置、程式碼整合到實操流程,完整解析 Srbac 使用全貌。
PostCreate),不可再分。PostManage = PostCreate + PostUpdate + PostDelete)。Editor = PostManage + CommentModerate)。繼承關係:Role → Task → Operation。使用者指派 Role,間接擁有所有下層權限。
| 表名 | 核心欄位 | 說明 |
|---|---|---|
| AuthItem | name (PK), type, description, bizrule, data | 儲存 Role/Task/Operation。type:0=Operation, 1=Task, 2=Role |
| AuthItemChild | parent, child (PK) | 父子繼承關係。parent=Role/Task, child=Task/Operation |
| AuthAssignment | itemname, userid (PK), bizrule, data | 使用者-角色指派。itemname 對應 AuthItem.name |
將 srbac 資料夾放入 protected/modules/。
'modules' => array(
'srbac' => array(
'userclass' => 'User', // 使用者模型類別
'userid' => 'id', // 使用者 PK 欄位
'username' => 'username', // 使用者名稱欄位
'debug' => false, // 生產環境必須 false,否則權限檢查失效
'pageSize' => 20,
'superUser' => 'Authority', // 超級角色名稱
'css' => 'srbac.css', // 可選主題
),
),
'components' => array(
'authManager' => array(
'class' => 'CDbAuthManager',
'connectionID' => 'db',
'itemTable' => 'AuthItem',
'itemChildTable' => 'AuthItemChild',
'assignmentTable' => 'AuthAssignment',
),
),
瀏覽 https://yourdomain/index.php?r=srbac/authitem/install,按提示建立資料表與預設資料。
// protected/components/SBaseController.php
class SBaseController extends Controller {
protected function beforeAction($action) {
$module = Yii::app()->getModule('srbac');
if (!$module->isInstalled() || $module->debug) {
return true; // 未安裝或除錯模式跳過檢查
}
// 組裝存取識別碼:Module.ControllerAction
$delimiter = $module->delimeter;
$moduleId = $this->module ? $this->module->id . $delimiter : '';
$controller = ucfirst($this->id);
$action = ucfirst($this->action->id);
$access = $moduleId . $controller . $action; // 例:Admin.UserCreate
// 白名單檢查
if (in_array($access, $this->allowedAccess())) {
return true;
}
// 核心權限檢查
if (Yii::app()->user->isGuest || !Yii::app()->user->checkAccess($access)) {
$this->onUnauthorizedAccess();
}
return true;
}
// 允許匿名存取的動作清單
protected function allowedAccess() {
return array('SiteLogin', 'SiteLogout', 'SiteIndex');
}
protected function onUnauthorizedAccess() {
if (Yii::app()->request->isAjaxRequest) {
echo '{"error":"access_denied"}';
Yii::app()->end();
} else {
$this->redirect(Yii::app()->user->loginUrl);
}
}
}
class PostController extends SBaseController {
// 自動受 SBaseController::beforeAction 保護
public function actionCreate() { ... }
public function actionUpdate($id) { ... }
public function actionDelete($id) { ... }
}
/srbac/authitem/manage → Create Operation → 輸入 PostCreate、PostUpdate、PostDelete(命名規則:ControllerAction,首字母大寫)。PostManage → 勾選關聯 PostCreate、PostUpdate、PostDelete。Editor → Assign 頁面將 Task 指派給 Role → Assign Users 將 Role 指派給使用者。bizrule 欄位存放 PHP 程式碼片段,執行時可用 $params 取得動態參數。
// 範例:只有文章作者才能編輯
$bizrule = 'return $params["post"]->author_id == $params["userId"];';
// 指派時附加參數
$authManager->assign('PostUpdate', $userId, $bizrule, array('post' => $postModel));
// 檢查時傳入參數
if (Yii::app()->user->checkAccess('PostUpdate', array('post' => $postModel))) {
// 允許編輯
}
| 現象 | 原因 | 解決 |
|---|---|---|
| 權限檢查完全不生效 | config 中 debug => true | 生產環境設為 false |
| 安裝器報表不存在 | authManager 元件未正確配置 connectionID | 檢查 components.db 與 authManager.connectionID |
| Operation 命名不生效 | 命名不符 ControllerAction 規則 | 嚴格遵循:PostCreate、UserDelete |
| 遞迴權限檢查死循環 | AuthItemChild 形成環狀參考 | 檢查父子關係,確保為 DAG |
Srbac 將 Yii RBAC 的威力釋放到極致:視覺化管理降低維護門檻、業務規則支援細粒度控制、模組化設計零侵入業務代碼。按照本文步驟落地,即可為專案建立企業級權限體系。