我的问题与此类似https://forum.yiiframework.com/t/rbac-restrict-backend-site/82416
我试着用下面的代码来实现它,但是它不起作用。我已经升级了yii 2,我已经做了移植。如何让它工作?
角色:管理员、用户
权限:canAccess后端
用户:管理员
分配:为admin分配角色管理员和权限canAccessBackend
/backend/controllers/SiteController.php
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (Yii::$app->user->can("canAccessBackend")) {
}
else {
throw new ForbiddenHttpException("You do not have permission to access this page.");
}
return true;
}
根据评论中的建议,另一个代码。它仍然不起作用。
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (Yii::$app->user->can("canAccessBackend")) {
return true;
}
throw new ForbiddenHttpException("You do not have permission to access this page.");
}
站点控制器.php
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['canAccessBackend'], //add only admin allowed
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* @return string
*/
public function actionLogin()
{
$this->layout = 'login';
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
/公共/配置/主.php
<?php
return [
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'modules' => [
'admin' => [
'class' => 'mdm\admin\Module',
]
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'authManager' => [
'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\PhpManager'
'defaultRoles' => ['admin', 'guest'],
],
'user' => [
'identityClass' => 'mdm\admin\models\User',
'loginUrl' => ['admin/user/login'],
],
],
];
1条答案
按热度按时间lb3vh1jj1#
您必须为此使用AccessFilter:上页:
在控制器中:
另外,在main.conf组件中添加以下内容,以将会话与前端分开:
希望能有所帮助。