This question has already been answered:

Hello! I make a personal account on yii2, and immediately there was a problem of authorization.
You need to redirect the guest user to the authorization page, in several controllers, because these controllers should NOT be available to the guest.
You can of course in each controller and in each action to perform a check, but this is not true.
I am sure that in yii it is possible to perform a check in a single method that is loaded before the actions. But the question is which one?

ps yii has just begun to study, so for many, the question may seem nubskim.

Reported as a duplicate by participants Alexey Shimansky , user194374, aleksandr barakin , cheops , Streletz Jun 28 '16 at 19:47 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

In each action, of course, checking is not necessary. For this there is AccessControl .

Inside the controller you can do this:

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

and then guests will not be allowed.

If you want a more global solution to the problem, without inheritance and creating separate components, you can solve it like this:

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

This code should be placed in the application configuration, it will be executed before each request. If desired, it can be modified to fit your specific needs.

I previously answered this question in English SO here .

Please note that in the latter case there should be no actions with the name login in controllers other than SiteController .