Override the Password Validation Logic Laravel

So I have this database that uses the same logic for the user, but there's a slight difference between the hash. Previous DB is used by bcrypt node which is slidely different so we need to make custom user provider to handle this.

While $2b$ and $2y$ are functionally equivalent in terms of Bcrypt behavior, Laravel's implementation does not recognize $2b$ directly.

Step 1.1: Create a Custom User Provider

Create a new file:
app/Auth/CustomUserProvider.php

<?php

namespace App\Auth;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Support\Facades\Hash;

class CustomUserProvider extends EloquentUserProvider
{
    /**
     * Validate a user's credentials.
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];
        $hashedPassword = $user->getAuthPassword();

        // Fix: Replace $2b$ with $2y$ dynamically for compatibility
        if (strpos($hashedPassword, '$2b$') === 0) {
            $hashedPassword = str_replace('$2b$', '$2y$', $hashedPassword);
        }

        return Hash::check($plain, $hashedPassword);
    }
}

Step 1.2: Extend the Auth Service Provider

In AppServiceProvider.php, bind the custom user provider:

use App\Auth\CustomUserProvider;
use Illuminate\Support\Facades\Auth;

public function boot()
{
    // Register the custom user provider
    Auth::provider('custom_user', function ($app, array $config) {
        return new CustomUserProvider($app['hash'], $config['model']);
    });
}

2. Modify Auth Configuration

In your config/auth.php file, set the custom provider as the default user provider:

'providers' => [
    'users' => [
        'driver' => 'custom_user', // Use the custom user provider
        'model' => App\Models\User::class,
    ],
],

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe