阅读资源代码后,您会发现 Laravel 验证用户的凭据vendor/src/Illuminate/src/Auth/EloquentUserProvider
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
- 所以,首先
getAuthPassword
在你的Models/User.php
class User extends Authenticatable
{
public function getAuthPassword()
{
return ['password' => $this->attributes['password']];
}
}
- 然后,添加自定义
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']);
}
}
- 然后,注册你
SelfEloquentUserProvider
的App/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']);
});
}
......
}
- 最后,在你的
config/auth.php
'providers' => [
'users' => [
'driver' => 'self-eloquent',
'model' => \App\User::class,
]
]
您可以通过这种方式轻松自定义自己的身份验证规则。