-1

我想在 laravel 8 中使用 md5 而不是 bcrypt 对密码进行哈希处理。在我的登录控制器 LoginController.php 中:

protected function credentials(Request $request)
        {
            return ['user_name' => $request->{$this->username()}, 'password' => md5($request->password), 'actif' => 'Y'];
        }

在我的 UserController 中,我有:

public function store(Request $request)
    {        
        $this->validationRules($request);        
        $user = new User();       
        $user->password = md5("00000000");
        $user->actif = 'Y';
        $user->user_name = $request->input('user_name');
        $user->save();

        return redirect('/users');
    }

新用户使用 md5 保存在数据库中,但是当我尝试登录时,它给了我这个错误:

These credentials do not match with our records
4

2 回答 2

1

阅读资源代码后,您会发现 Laravel 验证用户的凭据vendor/src/Illuminate/src/Auth/EloquentUserProvider

public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];
    return $this->hasher->check($plain, $user->getAuthPassword());
}
  1. 所以,首先getAuthPassword在你的Models/User.php
class User extends Authenticatable
{
    public function getAuthPassword()
    {
        return ['password' => $this->attributes['password']];
    }
} 
  1. 然后,添加自定义SelfEloquentUserProvider扩展自vendor/src/Illuminate/src/Auth/EloquentUserProvider.php
namespace App\Libs;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Str;

class SelfEloquentUserProvider extends EloquentUserProvider
{
    /**
     * Validate a user against the given credentials.
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param array $credentials
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        $plain = $credentials['password'];
        $authPassword = $user->getAuthPassword();
 
        return hash_equals(md5($plain), $authPassword['password']);
    }
}
  1. 然后,注册你SelfEloquentUserProviderApp/Providers/AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \Auth::provider('self-eloquent', function ($app, $config) {
            return New \App\Libs\SelfEloquentUserProvider($app['hash'], $config['model']);
        });
    }
    ......
}
  1. 最后,在你的config/auth.php
'providers' => [
    'users' => [
        'driver' => 'self-eloquent',
        'model' => \App\User::class,
    ]
]

您可以通过这种方式轻松自定义自己的身份验证规则。

于 2021-02-20T15:14:11.283 回答
0

您需要编写 LOGIN 控制器。

在带有 AUTH 包( Illuminate\Foundation\Auth\AuthenticatesUser s)的 Laravel 7 中,您可以访问:

  • Http > 控制器 > 身份验证 > LoginController.php

您必须使用以下方法重写 AuthenticatesUsers 特征:

protected function attemptLogin(Request $request)
{
    // Your login logic
}

如果您使用其他包,方法会有所不同,如果是这种情况,请查看您的包的文档。

于 2021-02-20T14:50:31.630 回答