Laravel Auth验证Token使用自定义Redis缓存的实现
背景
随着项目用户规模的不断扩大,接口调用频率显著增加,为减轻数据库的承载压力,计划引入Redis来存储Token。
调研
检查config/auth.php配置文件,发现当前用户驱动依赖EloquentUserProvider服务提供器。进一步追踪源码,确认该提供器位于vendor/laravel/framework/src/Illuminate/Auth目录下的EloquentUserProvider.php文件中。
<?php
namespace Illuminate\Auth;
use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class EloquentUserProvider implements UserProvider
{
/**
* The hasher implementation.
*
* @var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* The Eloquent user model.
*
* @var string
*/
protected $model;
/**
* Create a new database user provider.
*
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param string $model
* @return void
*/
public function __construct(HasherContract $hasher, $model)
{
$this->model = $model;
$this->hasher = $hasher;
}
/**
* Retrieve a user by their unique identifier.
*
* @param mixed $identifier
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifier)
{
return $this->createModel()->newQuery()->find($identifier);
}
...
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
...
}
实现代码
为了在现有Auth验证机制之上叠加Redis缓存层,最简便的方式是继承EloquentUserProvider类,并对关键方法进行重写。
基于此思路,新建RedisUserProvider.php文件以定义新的用户提供逻辑。
<?php
namespace App\Providers;
use Illuminate\Auth\EloquentUserProvider;
use Cache;
class RedisUserProvider extends EloquentUserProvider
{
public function __construct($hasher, $model)
{
parent::__construct($hasher, $model);
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (!isset($credentials['token'])) {
return;
}
$token = $credentials['token'];
$redis = Cache::getRedis();
$userId = $redis->get($token);
return $this->retrieveById($userId);
}
}
接着在AuthServiceProvider.php中进行配置修改。
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
//将redis注入Auth中
Auth::provider('redis',function($app, $config){
return new RedisUserProvider($app['hash'], $config['model']);
});
}
最后,修改config/auth.php中的auth驱动配置,将其切换为redis。
后续
代码修改完成后测试登录功能,发现无法成功登录,系统持续提示用户名或密码错误。经排查,用户认证流程涉及特定方法调用。
auth('web')->once($credentials);然后看是在
Illuminate\Auth\SessionGuard文件中用到了RedisUserProvider文件中retrieveByCredentials方法中对用户进行密码验证,
针对上述问题,对RedisUserProvider文件中的相关逻辑进行了修正。
<?php
namespace App\Providers;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Cache;
class RedisUserProvider extends EloquentUserProvider
{
public function __construct($hasher, $model)
{
parent::__construct($hasher, $model);
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
if(isset($credentials['phone']) && isset($credentials['password'])){
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
$token = $credentials['token'];
$redis = Cache::getRedis();
$userId = $redis->get($token);
return $this->retrieveById($userId);
}
}
修正后,登录功能恢复正常,问题解决。
以上这篇Laravel的Auth验证Token验证使用自定义Redis的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。