在YII2中无法访问时,设置禁用(#403)的默认页面

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

这是我在ShippingController中行为函数:

public function behaviors()
        {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    // deny all POST requests
//                        [
//                        'actions' => ['index', 'create'],
//                        'allow' => TRUE,
//                    ],
                        [
                        'actions' => ['index', 'create', 'init'],
                        'allow' => true,
                        'roles' => ['user2','user3'],
                        'denyCallback' => function()
                            {

                     redirect to address/index if user 2 cant access redirect to address/create if user3 cant access
                            //redirect here
                            }
                    ],
                // everything else is denied
                ],
            ],
        ];

        }

如何处理此问题!?如果角色为:user2无法访问和重定向到address/create,如果角色:user3无法访问

f3temu5u

f3temu5u1#

我假设你在yii中使用的是RBAC系统。检查配置文件:

'authManager'  => [
    'class' => 'yii\rbac\DbManager',
],

或者“yii\rbac\PHP管理器”。
以下是对我有效的方法:

'actions' => ['index', 'create', 'init'],
'allow' => false,
'roles' => ['user2','user3'],
'denyCallback' => function()
     {
        $user = Yii::$app->user;
        if ($user->can('user2')) {
           return Yii::$app->getResponse()->redirect(['/address/index']);
        } else {
           return Yii::$app->getResponse()->redirect(['/address/create']);
        }
     }

规则的'allow'选项应该被设置为false,这样denyCallback才能被调用。你可以在“yiisoft/yii2/filters/AccessControl.php”的第120行看到。

相关问题