简体   繁体   English

Laravel 8 身份验证:auth::attemp 始终返回 false

[英]Laravel 8 Authentication: auth::attemp always return false

I'm using Laravel 8 and trying to authenticate an user (sign in)我正在使用 Laravel 8 并尝试对用户进行身份验证(登录)

My model:我的 model:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;
class AccountModel extends Model implements AuthenticatableContract
{
    use HasFactory;
    use Authenticatable;
    protected $table='Accounts';
    protected $primaryKey= 'Username';
    public $incrementing = false;
    protected $fillable = ['Username','Password','RoleID','RegisteredAt','Status','updated_at','created_at'];
    public function getAuthPassword()
    {
        return $this->Password; 
    }
    public function getAuthIdentifier()
    {
        return $this->Username; 
    }
    protected $hidden = [
        'remember_token'
    ];        
}

My controller我的 controller

<?php
namespace App\Http\Controllers\Admin;
use App\Models\AccountModel;
use App\Http\Controllers\Controller;
use Illuminate\Routing;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Cookie;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

class LogInController extends Controller
{
    function index()
    {
        return view('Admin.LogIn');
    }
    public function Username()
    {
        return 'Username';
    }
    function loginaction($usn,$pw)
    {
        $credentials = [
            'Username'=>$usn,
            'password'=>$pw,
        ];
            if (Auth::guard('admin')->attempt($credentials)) {
                $credentials->cookie()->regenerate();
                return redirect()->intended('/Admin/Home');
            }
            else
                return $credentials;
    }

config/auth.php config/auth.php

<?php

return [
    'defaults' => [
        'guard' => 'admin',
        'passwords' => 'admin',
    ],
    'guards' => [
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'admin',
            'hash' => false,
        ],
    ],
    'providers' => [
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Models\AccountModel::class,
        ],
    ],


    'passwords' => [
        'admin' => [
            'provider' => 'admin',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],


    'password_timeout' => 10800,

];

Migartion迁移

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Accounts', function (Blueprint $table) {
            $table->string('Username');
            $table->string('Password');
            $table->int('RoleID');
            $table->timestamp('RegisteredAt');
            $table->string('Status');
            $table->timestamp('updated_at');
            $table->timestamp('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('Accounts');
    }
}

Blade (Ajax worked, data sent) Blade(Ajax 工作,数据发送)

  <div class="wrap-input100 validate-input" id="typeusername" data-validate="Nhập tên đăng nhập">
            <input class="input100" id="usn" type="text" name="username" placeholder="Username">
            <span class="focus-input100" data-placeholder="👨‍"></span>
            <p class="error-login" style="color:red;font-size:13px;display:none;"> ! Chưa nhập tên đăng nhập </p>
        </div>
        <div class="wrap-input100 validate-input" id="typepassword" data-validate="Nhập mật khẩu">
            <input class="input100" id="psw" type="password" name="pass" placeholder="Password">
            <span class="focus-input100" data-placeholder="🔒"></span>
            <p class="error-login" style="color:red;font-size:13px;display:none;"> ! Chưa nhập mật khẩu </p>
        </div>
<div class="container-login100-form-btn">
            <button class="login100-form-btn" onclick="login()">Login</button>
        </div>
<script>
    function login()
    {
        var usn = $("#usn").val();
        var pass = $("#psw").val();
         $.get("{{route('bLogIn')}}/" + usn +"/" + pass , function (res) {
                if (res =='Fail')
                { 
                    $(".alerterror").css("display", "block");
                } 
                else
                    window.location.href = "{{route('bHome')}}";
            });
    }
</script>

I'm using Ajax to send data from view to controller.我正在使用 Ajax 将数据从视图发送到 controller。 It sent, the controller have it, my code also use Where clause to check the right table - 'Accounts' i save in my MySQL database.它发送了,controller 有它,我的代码还使用 Where 子句检查正确的表 - 我保存在我的 MySQL 数据库中的“帐户”。 Username and password exist but attemp still return false.用户名和密码存在,但尝试仍然返回 false。

Can Anyone Tell Me Why It Cant Run Successfully?谁能告诉我为什么它不能成功运行?

I think you are using different field name for password.By default its small letter password but in your case first letter is capital Password so you can do define an accessor like below我认为您使用不同的字段名称作为密码。默认情况下,它的小写字母password ,但在您的情况下,第一个字母是大写Password ,因此您可以定义如下所示的访问器

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

Updated I have tested and solved using following.更新我已经使用以下测试并解决了。 Your Account model should implement following methods您的Account model应实现以下方法

 public function getAuthIdentifierName()
    {
        return $this->Username;
    }

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

and in your controller you should use在你的 controller 你应该使用

 $credentials = [
            'Username'=>"test",
            'password'=>"admin@123",
        ];

while passing password field it should be lower case then your model method will convert it to according to model class if (Auth::attempt($credentials)) {在传递密码字段时,它应该是小写,然后您的 model 方法将根据 model class 将其转换为

Updated Answer更新的答案

AccountModel账户模型

<?php
namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;


class AccountModel extends   Authenticatable
{
    use HasFactory, Notifiable;

    protected $table='accounts';
    protected $primaryKey= 'Username';
    public $incrementing = false;
    protected $fillable = ['Username','Password','RoleID','RegisteredAt','Status','updated_at','created_at'];
    protected $hidden = [
        'remember_token'
    ];
  //  protected $guard = 'admin';


    public function getAuthIdentifier(){
        return $this->Username;
    }
    public function getAuthIdentifierName()
    {
        return $this->Username;
    }

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

}

In Controller在 Controller

 $credentials = [
            'Username'=>"test",
            'Password'=>"admin@123",
        ];

        if (Auth::attempt($credentials)) {
          //  $credentials->cookie()->regenerate();
           dd(auth()->user());
        }
        else
            return $credentials;

i fixed it.我修好了它。 because in my EloquentUserProvider, password is hashed before checked so it's required at least 60 character.因为在我的 EloquentUserProvider 中,密码在检查之前经过哈希处理,因此至少需要 60 个字符。 i think it's unnecessary so i changed to compare 2 strings function我认为没有必要,所以我改为比较 2 个字符串 function

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

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