Yii2 global filter/behavior to force user to authenticate first
11,559
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
Related videos on Youtube
Author by
Jap Mul
Updated on June 04, 2022Comments
-
Jap Mul 12 months
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' => ['@'], ], ], ], ]; }
-
robsch over 8 yearsHint: this code adds an behavior to the application. It doesn't have to be part of components - it must be part of the config itself. So this is why jagsler wrote below components, not in components. And
'as someNameHere' => ...
is the syntax for adding behaviors. Look here for doc. I just write this because I have spend some hours finding that out. -
israr about 8 yearsVery nice. It saves my time.
-
robsch almost 8 yearsAnother note: you need to have a controller and an action
site/login
because this gets called if the user is not logged in and no rule applies. This can be changed in the configuration (see here for more information) if the login action has another name or is another controller. -
The Humble Rat about 7 yearsIf you exclude
error
from the allowed actions it causes a white screen. Previously you could use this to redirect everyone that was not logged in, however, you can no longer redirect 404 errors etc since some updates. I found the current way here github.com/yiisoft/yii2/issues/11054#issuecomment-198310042 -
Mirjalal over 6 years@robsch thanks very much! Your comment saved my time!