Yii2 限制访问 RBAC 模块本身
Yii2 restricting access to RBAC Module itself
如何限制对 RBAC 模块本身的访问?
我正在使用yii\rbac\DbManager
并且我在后端创建了一个模块(授权)用于权限分配,创建授权项目,现在我想确保只有管理员可以访问这个模块!
我在控制器中使用了一些东西并且工作正常。
use yii\filters\AccessControl;
class MyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete'], //only be applied to
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update','delete'],
'roles' => ['admin'],
],
],
],
.........
我已经把它放在 Authorization.php init 函数中但是没有任何反应,所有的 auth 控制器都可以访问。
public function init()
{
if(\Yii::$app->user->can('admin'))
parent::init();
// custom initialization code goes here
}
更新
backend/config/main.php
'modules' => [
'authorization' => [
'class' => 'backend\modules\authorization\Authorization',
],
],
在你的模块中class你可以添加这个方法
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (!\Yii::$app->user->can('admin')) {
throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page.');
}
return true;
}
如何限制对 RBAC 模块本身的访问?
我正在使用yii\rbac\DbManager
并且我在后端创建了一个模块(授权)用于权限分配,创建授权项目,现在我想确保只有管理员可以访问这个模块!
我在控制器中使用了一些东西并且工作正常。
use yii\filters\AccessControl;
class MyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete'], //only be applied to
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update','delete'],
'roles' => ['admin'],
],
],
],
.........
我已经把它放在 Authorization.php init 函数中但是没有任何反应,所有的 auth 控制器都可以访问。
public function init()
{
if(\Yii::$app->user->can('admin'))
parent::init();
// custom initialization code goes here
}
更新
backend/config/main.php
'modules' => [
'authorization' => [
'class' => 'backend\modules\authorization\Authorization',
],
],
在你的模块中class你可以添加这个方法
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (!\Yii::$app->user->can('admin')) {
throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page.');
}
return true;
}