简体   繁体   English

Yii2身份验证失败

[英]Yii2 Authentication fails

Today i came across with a probleme in Yii2 Authentication. 今天,我在Yii2身份验证中遇到了问题。 I implemented succesfully but when i try to log in every time it shows me the following error: 我成功实现了,但是每次尝试登录时都显示以下错误:

在此处输入图片说明

After i refresh the page 1 or 2 times the error goes off and everything works properly. 在刷新页面1或2次后,错误消失并且一切正常。 My first tought was to add the database field auth_key (32) varchar but it didn't solved the issue. 我的第一个任务是添加数据库字段auth_key(32)varchar,但是并没有解决问题。

Here is my User.php: 这是我的User.php:

<?php

namespace app\models;

use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;


class User extends ActiveRecord implements \yii\web\IdentityInterface
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'felhasznalo';
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByFelhasznalonev($felhasznalonev)
    {
        return static::findOne(['felhasznalonev' => $felhasznalonev]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_Key;
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_Key === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->jelszo === sha1($password);
    }
}

The login action: 登录操作:

public function actionLogin()
    {

        if (!\Yii::$app->user->isGuest) {
            if (empty($_SESSION['ablak_id'])) {
                $_SESSION['ablak_id'] = Yii::$app->request->post('a_id');
            }
            else {
                return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
            }
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            $session = Yii::$app->session;
            $session->set('ablak_id', Yii::$app->request->post('ablak_id'));
            return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
        }

        //Lekérdezzük az elérhető rendelők nevét majde elküldjük kimenetre
        $ablakok = Ablak::find()->all();

        return $this->render('login', [
            'model' => $model,
            'ablakok' => $ablakok,
        ]);
    }

And the LoginForm.php: 和LoginForm.php:

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user = false;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByFelhasznalonev($this->username);
        }

        return $this->_user;
    }
}

This is the table structure for the users table(felhasznalok == users in hungary) 这是用户表的表结构(felhasznalok ==匈牙利用户)

在此处输入图片说明

Any ideas for the problem? 对这个问题有什么想法吗?

Thank your for Your answers! 感谢您的回答!

Gábor GABOR

try changing the getUser function in your LoginForm into: 尝试将LoginForm中getUser函数更改为:

public function getUser()
{
    if ($this->_user === false) {
        $this->_user = User::findByFelhasznalonev($this->username);

        //generate auth_key for a new created User
        $this->_user->generateAuthKey();
    }

    return $this->_user;
}

It is simply a typo, you should use auth_key instead of auth_Key : 这只是一个错字,您应该使用auth_key而不是auth_Key

public function validateAuthKey($authKey)
{
    return $this->auth_key === $authKey;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM