首页 > 解决方案 > Laravel 7 身份验证尝试返回 false

问题描述

我似乎找不到解决方案,我的Auth::attempt()函数总是返回 false,我找不到我做错了什么。这是我对 tblusers 的迁移:

public function up()
{
    Schema::create('tblusers', function (Blueprint $table) {
        $table->id();
        $table->string('Username')->unique();
        $table->string('FirstName');
        $table->string('LastName');
        $table->string('ContactNo')->unique();
        $table->string('Email')->unique();
        $table->timestamp('EmailVerifiedOn')->nullable();
        $table->string('Password');
        $table->integer('AddedBy');
        $table->rememberToken();
        $table->timestamps();
    });
}

我定制了User模型:

class User extends Authenticatable
{

    protected $table = 'tblusers';
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'Password', 'remember_token',
    ];
}

因此密码在查询中不再可见User::,所以我Auth::attempt改用。这就是我插入哈希密码的方式:

    $password = $request->Password;
    $hash = Hash::make($password);

    $insertData = array(
        ...
        'Email' => $email,
        'Password' => $hash,
        'AddedBy' => 0,
        'created_at' => date('Y-m-d H:i:s')
    );

这就是我使用Auth::attempt的方式,有人可以指出我做错了什么,因为它总是返回错误。

        $credentials = array(
            "Username" => $username,
            "Password" => Hash::make($password)
        );
        
        return dd(Auth::attempt($credentials));
        if (Auth::attempt($credentials)) {
            $response = true;
        } else {
            $response = false;
        }   

标签: phplaravel

解决方案


传递给的“密码”字段attempt 必须命名password(完全像这样)。此外,您还需要调整getAuthPassword模型上的方法,因为默认情况下它期望数据库中的密码字段为“密码”。如果这是一个新项目和数据库,我强烈建议您遵循约定,但如果您想保持原样,则需要进行以下更改:

$credentials = [
    'Username' => $username,
    'password' => $password,
];

请注意,密钥是password并且我们没有对密码进行哈希处理,因为它需要密码的纯文本版本,因此它最终可以对其进行哈希检查。

在此模型上,您将需要覆盖该getAuthPassword方法:

public function getAuthPassword()
{
    return $this->Password;
}

推荐阅读