Am implementing authentication in yii2 basic project Login action seems to working fine
public function actionLogin()
{
$this->layout = "login-layout";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if (Yii::$app->user->isGuest) {
var_dump("guest"); die();
} else {
var_dump("This is user"); die();
}
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
I have configured as before request in config.php as shown below
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'actions' => ['login'],
],
[
'allow' => true,
'roles' => ['@'],
],
],
'denyCallback' => function () {
return Yii::$app->response->redirect(['site/login']);
},
],
My problem is even if user is successfully authenticated still I can't access other pages keep redirecting to the login page Please help me to resolve this.
Finally I was able to resolve this after some hours of debugging. The problem was caused by findIdentity method in my User model, Since I was creating it to return null as shown below
public static function findIdentity($MemberId) {
$user = self::find();
return ;//static($user);
}
So I have changed it to
public static function findIdentity($MemberId) {
$user = self::find()->where(['MemberId' => $MemberId])->one();
return $user;
}
Now, it works fine so the problem was not in as beforeRequest instead the application was not finding the actual user.