Yii 2 redirecting to Login if Guest visit the website
11,580
Solution 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
Solution 2
There are two options:
- You can use the AccessControl as mentioned by @Maksym Semenykhin
-
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);
Solution 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
],
],
];
}
Comments
-
RosS over 1 year
I need some advice how to make redirecting to login if someone does not login into the website and he is only Guest
-
RosS almost 8 yearsI should put it in every controller or ...?
-
Bhavin Thummar almost 5 years@MaksymSemenykhin Can i use in this way
return Yii::$app->getResponse()->redirect(SITE_URL.'login');
? Why are you writed getResponse function ? what is use of it? I have written this way but I am not getting referrer on login page.