1.先在main,php中配置
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
2.在cmd命令中,项目目录下执行
yii migrate --migrationPath=@yii/rbac/migrations/
创建了四张表
auth_item 该表存放授权条目(译者注:即角色和权限)。
auth_item_child 该表存放授权条目的层次关系。角色-权限的关联表
auth_assignment 该表存放授权条目对用户的指派情况。用户-角色的关联表
auth_rule 该表存放规则。
然后手动添加数据 或通过代码生成
3.创建MyController.php其他控制器继承这个控制器
<?php
namespace frontend\controllers;
use Yii;
use yii\web\ForbiddenHttpException;
use yii\web\Controller;
use common\models\User;
class MyController extends Controller
{
public function beforeAction($action)
{
if(parent::beforeAction($action)){
$controllerId=$action->controller->id;
//获取控制器名称
$actionId=$action->id;
//获取方法名称
$nodeName=$controllerId.'/'.$actionId; //abc_index
$user=\Yii::$app->user->identity;
//验证是否登录
if(!$user){
$this->redirect(['/']);
}
if(\Yii::$app->user->can($nodeName)){
return true;
}else{
throw new ForbiddenHttpException('对不起,您还没获此操作的权限');
}
}else{
return false;
}
}
}