Yii2 global filter/behavior to force user to authenticate first

后端 未结 2 442
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 03:15

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

相关标签:
2条回答
  • 2020-12-05 03:22

    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.

    0 讨论(0)
  • 2020-12-05 03:40

    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

    0 讨论(0)
提交回复
热议问题