Home > front end >  Laravel 9 Hash::check() always returns false using Fortify
Laravel 9 Hash::check() always returns false using Fortify

Time:09-13

Using tinker:

>>> $user = User::create(['name_first' => 'test', 'name_last' => 'last', 'password' => Hash::make('password'), 'email' => '[email protected]']);

=> App\Models\User {#4771
     name_first: "test",
     name_last: "last",
     password: "$2y$10$9Yjm2xf0PBWdvbw42q3i5.7xW8UoXyLtDHHFI8LTerRIV3R0efvbi",
     email: "[email protected]",
     uuid: Ramsey\Uuid\Lazy\LazyUuidFromString {#4732
       uuid: "0ef8dfaf-1068-4349-a4fe-5f0f23a30e58",
     },
     updated_at: "2022-09-12 23:17:06",
     created_at: "2022-09-12 23:17:06",
     id: 105,
   }

This returns true as expected.

>>> Hash::check('password', $user->password);
=> true

I copy pasted this code in my FortifyServiceProvider.php: https://laravel.com/docs/9.x/fortify#customizing-user-authentication

When trying to log in with the User I created using tinker using my frontend (Vue 3 SPA with Sanctum and Fortify), I keep getting the message These credentials do not match our records.. Why is that?

By the way, for viewing purposes, I commented password from the $hidden array in User.php

CodePudding user response:

It returns correctly for me because I have a User model with no accessors or mutators.

I would guess that you have a mutator on the user model that hashes the password for you, so you only need to pass plaintext password into the create function.

At present you are possibly hashing the password twice.

CodePudding user response:

Man, I feel so stupid. I'm using a fresh L9 application and copied bits of code from another (older) app. I also copied this bit of code in my User.php model:

public static function boot()
{
    parent::boot();
        
    static::creating(function (User $user) {
        $user->uuid = str()->uuid();

        $user->password = Hash::make(str()->random(20));
    });
}

This is used because the app I'm working on lets the administrators create new users. This immediately notifies the user to set up a new password.

But I copied this BEFORE seeding all my test data, hence why password wouldn't work. But I only commented the boot method out, AFTER the seeding was done. That's why authentication seemed to work for new users created with Tinker and not the seeded users.

  • Related