Yii2 RBAC只允许管理员进行后端访问

h5qlskok  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(195)

我的问题与此类似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'],
        ],

    ],
];
lb3vh1jj

lb3vh1jj1#

您必须为此使用AccessFilter:上页:

use yii\filters\AccessControl;

在控制器中:

/**
         * {@inheritdoc}
         */
        public function behaviors()
        {
            return [
                'access' => [
                    'class' => AccessControl::className(),
                    'only' => ['login', 'logout', 'index'],
                    'rules' => [
                         [
                              'allow' => true,
                              'actions' => ['login'],
                              'roles' => ['?'],
                        ],
                        [
                            'allow' => true,
                            'actions' => ['index', 'logout'],
                            'roles' => ['canAccessBackend'], //add only admin allowed
                        ],
                    ],
//                  Use this property to throw any message or set flash message 
                    //'denyCallback'  => function ($rule, $action) {
                    //   \Yii::$app->session->setFlash('error', 'This section is only for registered users.');
                    //   \Yii::$app->user->loginRequired();
                ],
            ];
        }

另外,在main.conf组件中添加以下内容,以将会话与前端分开:

'session' => [
            // this is the name of the session cookie used for login on the backend
            'name' => 'advanced-backend',
        ],

希望能有所帮助。

相关问题