Yii2 Global Filter / Behavior for Force User Authentication

In my Yii2 application, I am trying to force all users to authenticate. If they have not yet been authenticated, they should be redirected to the login page.

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

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

How can I get the same behavior in Yii2? I know that I can use the behavior for this, but I do not want to add this behavior to my main configuration file, so all requests are first checked for authentication.

The working behavior method is as follows:

 // Yii2 public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login', 'error'], 'allow' => true, ], [ 'allow' => true, 'roles' => ['@'], ], ], ], ]; } 
+23
php yii rbac yii2
source share
2 answers

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' => ['@'], ], ], ], 

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

+28
source share

In fact, I do not understand Yii2 (but very much in Yii1).

One solution that can be used in Yii1, and I assume that in Yii2 there is a filter method in the class of the main controller. Typically, one controller serves as the master controller. If you don’t have it, create it and everyone should expand it. You can probably implement this not as a filter, but in other methods of this "main controller" (init ()?) If all the actions go through the controller class, then you are configured.

-one
source share

All Articles