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

set default page for Forbidden (#403) when cant access in YII2

这是我在 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/index 并重定向到 address/create 如果角色:user3 无法访问

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

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

或'yii\rbac\PhpManager'.

以下是对我有用的方法:

'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 行看到。