What is best way to redirect on login page in yii2

左心房为你撑大大i 提交于 2020-01-13 03:55:09

问题


If user is not logged in then user should have to be redirect on login page, for that i found function which is working fine for me, i used below function

public function beforeAction($action)
{        
    if (\Yii::$app->getUser()->isGuest &&
        \Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
    ) {
        \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
    }
    return parent::beforeAction($action);
}

This is working fine for me, but for this i need to add function in every controller, what i want to do, i need common function where can i perform this action, So can anyone please tell me what is best way to do this ?


回答1:


You need to add below code in config/web.php after components part.

'as beforeRequest' => [  //if guest user access site so, redirect to login page.
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
],



回答2:


Actually if user does not have rights Yii redirects him to login page by it self. You can change loginUrl if you have another one. Or you can implement own redirect if for example you use ajax. http://www.yiiframework.com/doc-2.0/yii-web-user.html

Here is explanation of Yii security http://www.yiiframework.com/doc-2.0/guide-security-authorization.html



来源:https://stackoverflow.com/questions/33296156/what-is-best-way-to-redirect-on-login-page-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!