问题
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