Yii2 global filter/behavior to force user to authe

2019-01-13 18:30发布

In my Yii2 application I'm trying to force all users to be authenticated. If they're not already authenticated they should be redirected to the login page.

In Yii1 I did this by creating a class that would check if a user was logged in and attaching that class to the onBeginRequest behavior in my main config file.

// Yii 1
'behaviors' => array(
    'onBeginRequest' => array(
        'class' => 'application.components.RequireLogin',
    )
),

How can I get the same behavior in Yii2? I know I can use behavior to do this, but I wan't to add this behavior to my main config file so all requests are first checked for authentication.

The working behaviors method looks like this:

// Yii2
public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['login', 'error'],
                    'allow' => true,
                ],
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
    ];
}

标签: php yii yii2 rbac
2条回答
贪生不怕死
2楼-- · 2019-01-13 18:45

Ok, so I had to add the following code below 'components' => [...]

 'as beforeRequest' => [
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [

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

Read more about the format: http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format

查看更多
forever°为你锁心
3楼-- · 2019-01-13 18:59

I'm actually not versed into Yii2 (but very much so into Yii1).

One solution that can be employed in Yii1 and I guess also in Yii2 is having a filter method in a master Controller class. Typically a single controller serves as a master controller. If you don't have one, create it and everyone should extend it. You can implement this probably not as a filter but in other methods of this 'master controller' (init() ?) If all activity is going through controller class then you're set.

查看更多
登录 后发表回答