Yii 2 redirecting to Login if Guest visit the website

人盡茶涼 提交于 2019-12-31 03:47:07

问题


I need some advice how to make redirecting to login if someone does not login into the website and he is only Guest


回答1:


use Yii;
use \yii\helpers\Url;

if ( Yii::$app->user->isGuest )
    return Yii::$app->getResponse()->redirect(array(Url::to(['site/login'],302)));

Use can use it in actions or views , but if you need to use it in lots of actions you probably need look at AccessControl and restrict access even before action is fired




回答2:


There are two options:

  1. You can use the AccessControl as mentioned by @Maksym Semenykhin
  2. You can use the option below especially when you would like the logged user to be returned to this page after login.

    public function beforeAction($action){
    if (parent::beforeAction($action)){
        if (Yii::$app->user->isGuest){
            Yii::$app->user->loginUrl = ['/auth/default/index', 'return' => \Yii::$app->request->url];
            return $this->redirect(Yii::$app->user->loginUrl)->send();
        }
    }}
    

    You can also create a custom 'Controller' class which inherits \yii\web\Controller then have all controllers that need authorization inherit your custom controller.

On the login function, replace the redirect part with the following code:

    $return_url = empty(Yii::$app->request->get('return'))? \yii\helpers\Url::to(['/admin/default/index']) :Yii::$app->request->get('return');
    return $this->redirect($return_url);



回答3:


Use the access section to set access to various actions in the controller.

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ],
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update','index'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
        ],
    ];
}


来源:https://stackoverflow.com/questions/38227467/yii-2-redirecting-to-login-if-guest-visit-the-website

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