Yii 2 redirecting to Login if Guest visit the website

前端 未结 3 1672
不知归路
不知归路 2021-01-21 19:31

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

相关标签:
3条回答
  • 2021-01-21 20:03

    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);
    
    0 讨论(0)
  • 2021-01-21 20:21

    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
                ],
            ],
        ];
    }
    
    0 讨论(0)
  • 2021-01-21 20:22
    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

    0 讨论(0)
提交回复
热议问题