Laravel的Auth验证Token验证使用自定义Redis的例子


Posted in PHP onSeptember 30, 2019

背景

项目用户量逐渐增大,接口调用次数越来越多,所以决定使用Redis存token,缓解数据库压力

调研

config/auth.php文件中发现用户的驱动使用的是EloquentUserProvider服务提供器,然后查找EloquentUserProvider.php 然后发现在vendor/laravel/framework/src/Illuminate/Auth文件下存在该文件

<?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类,重写

retrieveByCredentials方法所以我们新建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的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
PHP 存取 MySQL 数据库的一个例子
Oct 09 PHP
asp和php下textarea提交大量数据发生丢失的解决方法
Jan 20 PHP
需要注意的几个PHP漏洞小结
Feb 05 PHP
PHP中call_user_func_array()函数的用法演示
Feb 05 PHP
解析func_num_args与func_get_args函数的使用
Jun 24 PHP
php中解析带中文字符的url函数分享
Jan 20 PHP
标准PHP的AES加密算法类
Mar 12 PHP
php实现文本数据导入SQL SERVER
May 17 PHP
PHP+shell脚本操作Memcached和Apache Status的实例分享
Mar 11 PHP
PHP  Yii清理缓存的实现方法
Nov 10 PHP
PHP针对中英文混合字符串长度判断及截取方法示例
Mar 31 PHP
PHP二维关联数组的遍历方式(实例讲解)
Oct 18 PHP
Laravel框架控制器的middleware中间件用法分析
Sep 30 #PHP
Laravel 已登陆用户再次查看登陆页面的自动跳转设置方法
Sep 30 #PHP
laravel实现登录时监听事件,添加登录用户的记录方法
Sep 30 #PHP
php7下的filesize函数
Sep 30 #PHP
laravel利用中间件防止未登录用户直接访问后台的方法
Sep 30 #PHP
laravel实现Auth认证,登录、注册后的页面回跳方法
Sep 30 #PHP
Laravel框架表单验证操作实例分析
Sep 30 #PHP
You might like
PHP 中执行系统外部命令
2006/10/09 PHP
发布一个迷你php+AJAX聊天程序[聊天室]提供下载
2007/07/21 PHP
javascript+php实现根据用户时区显示当地时间的方法
2015/03/11 PHP
PHP使用内置函数生成图片的方法详解
2016/05/09 PHP
Yii 2中的load()和save()示例详解
2017/08/03 PHP
Yii redis集合的基本使用教程
2020/06/14 PHP
文字幻灯片
2006/06/26 Javascript
JS window.opener返回父页面的应用
2009/10/24 Javascript
基于jsTree的无限级树JSON数据的转换代码
2010/07/27 Javascript
实例解析jQuery中proxy()函数的用法
2016/05/24 Javascript
js实现获取两个日期之间所有日期的方法
2016/06/17 Javascript
如何用JS判断两个数字的大小
2016/07/21 Javascript
H5基于iScroll实现下拉刷新和上拉加载更多
2017/07/18 Javascript
nodejs+express搭建多人聊天室步骤
2018/02/12 NodeJs
[28:48]《真视界》- 2017年国际邀请赛
2017/09/27 DOTA
python类定义的讲解
2013/11/01 Python
python文件和目录操作函数小结
2014/07/11 Python
Python中的装饰器用法详解
2015/01/14 Python
使用Python3 编写简单信用卡管理程序
2016/12/21 Python
Python探索之Metaclass初步了解
2017/10/28 Python
Django中login_required装饰器的深入介绍
2017/11/24 Python
Python Scrapy多页数据爬取实现过程解析
2020/06/12 Python
python中lower函数实现方法及用法讲解
2020/12/23 Python
详解html5页面 rem 布局适配方法
2018/01/12 HTML / CSS
柯基袜:Corgi Socks
2017/01/26 全球购物
Meli Melo官网:名媛们钟爱的英国奢侈手包品牌
2017/04/17 全球购物
美国汽车零部件和配件网站:CarParts
2019/03/13 全球购物
关于环保的建议书400字
2014/03/12 职场文书
计算机专业应届生求职信
2014/04/06 职场文书
财务情况说明书范文
2014/05/06 职场文书
年度考核登记表个人总结
2015/03/06 职场文书
电影圆明园观后感
2015/06/03 职场文书
家长会感言
2015/08/01 职场文书
中国梦党课学习心得体会
2016/01/05 职场文书
SpringBoot SpringEL表达式的使用
2021/07/25 Java/Android
Promise静态四兄弟实现示例详解
2022/07/07 Javascript