Yii2需要所有Controller和Action才能登录 [英] Yii2 require all Controller and Action to login

查看:344
本文介绍了Yii2需要所有Controller和Action才能登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的站点控制器中,我这样写

In my sitecontroller I write like this

    'access' => [
        'class' => AccessControl::className(),
        'rules' => [
            [
                'actions' => ['login', 'error'],
                'allow' => true,
            ],
            [
                'actions' => ['logout', 'index' ,'call-back'], // add all actions to take guest to login page
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ],

因此,如果我转到索引或回叫操作,我将重定向到登录页面. 但是我必须对每个控制器执行所有操作. 你能告诉我最好的方法吗?

so If I go to index or call-back action,I'll redirected to login page. but I have to do it for all action to each controller. Could you tell me the best way to do it?

推荐答案

将此规则放在rules部分的开头:

Place this rule in the beginning of the rules section:

[
    'allow' => true,
    'roles' => ['@'],
],

省略actions表示所有操作.

因此您的AccessControl配置将如下所示:

So your AccessControl config will be like this:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],

                // ...
            ],
        ],
    ];
}

请记住,规则是按声明顺序应用的.

Keep in mind that rules are applied in order they are declared.

要在不继承的情况下全局进行操作,请在应用程序配置中的components声明下面(不在内部!)添加as beforeRequest数组:

To do it globally without inheritance, add the as beforeRequest array below (not inside!) the components declaration in your application config:

'components' => [ ... ],
'as beforeRequest' => [
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'allow' => true,
            'actions' => ['login'],
        ],
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
    'denyCallback' => function () {
        return Yii::$app->response->redirect(['site/login']);
    },
],

此代码将在每个请求之前运行,并阻止来宾执行除login之外的所有操作.

This code will run before each request and block all actions except login for guests.

确保除SiteController以外的其他控制器中没有任何login操作.如果存在(例如,它们出于不同的目的),请在相应的控制器中明确阻止它们.但这是非常罕见的情况.

Make sure that there is no login action in other controllers than SiteController. If there are (and for example they are for different purposes), block them explicitly in according controllers. But it's pretty rare case.

这篇关于Yii2需要所有Controller和Action才能登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆