Initial Login Page in Yii 2.0

3k views Asked by At

So I have seen post on how to set the default route in Yii 1 whereby the initial page is the login page, but no posts on how to do this in Yii 2.

What I need is for all users to first login and to then be able to use CRUD functions, with some users able to do more than others.

For your information, I am using the basic template.

2

There are 2 answers

1
ScaisEdge On

try in basic\config\web.php

add 'loginUrl' => ['user/login'], to user in components

'components' => [
    'request' => [
        // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
        'cookieValidationKey' => '',
    ],
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
        'loginUrl' => ['user/login'],
    ],

// ...

]

0
taiff On

Just thought to make the solution visible here. Found via at https://www.yiiframework.com/forum/index.php/topic/54255-newbies-question-to-yii2-how-can-i-force-user-to-login/ by vishwasrao, and a similar post here Yii2 global filter/behavior to force user to authenticate first by jagsler.

For Basic template, in config/web.php, add the following 'as access' section:

 'components' => [ ... ],
 'as access' => [
    'class' => \yii\filters\AccessControl::className(),//AccessControl::className(),
    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [
            'actions' => ['logout', 'index'], // add all actions to take guest to login page
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
 ],
 'params' => $params,

Hope this helps anyone still looking for this.