Laravel常用扩展sanctum与medoo的使用

2,215次阅读
没有评论

安装 laravel/sanctum 扩展
1、下载sanctum扩展库

cd /usr/local/nginx/html/laravel/
composer require laravel/sanctum

生成配置文件

php artisan vendor:publish –provider=”Laravel\Sanctum\SanctumServiceProvider”

2、为config/sanctum.php配置文件设置到期时间,sanctum是以分钟为单位

‘expiration’ => 60 * 2,

3、最后,你需要执行数据库迁移文件。Sanctum 将创建一个数据库表用于存储 API 令牌:
这一步生成存放token验证的数据表

php artisan migrate

4、在 app/Http/Kernel.php 文件中将 Sanctum 的中间件添加到你的 api 中间件组中:

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

‘api’ => [
EnsureFrontendRequestsAreStateful::class,
‘throttle:60,1’,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

使用sanctum进行token验证实例
参考文档:https://learnku.com/docs/laravel/7.x/sanctum/7510
1、创建user表模型,并继承sanctum的user类(app\Model\UserModel.php)
2、创建loginApi登录接口,用于生成token并将token存入redis缓存,并根据token失效时间’expiration’ => 60 * 2设置redis值的失效时间,因为sanctum是以分钟为单位,redis是以秒为单位需要乘60换算
3、通过获取头部信息在__construct获取缓存的用户信息,并通过userInfoApi接口返回获取用户详情
4、在路由加入auth:sanctum中间件保护路由,指定哪些接口访问需要使用到token验证的

token签名
1、实现逻辑app\Http\Controller\Test\IndexController.php

引用User模型与缓存类

use App\Model\UserModel;
use Illuminate\Support\Facades\Cache;

protected $s_user;

public function __construct(Request $request)
{
    //登录成功后,访问其他方法时,获取请求头存放的token信息进行验证
    $BearerToken = $request->server('HTTP_AUTHORIZATION');
    $authToken =str_replace('Bearer ','',$BearerToken);
    //根据token值作为键名从redis缓存中获取用户详细信息
    $this->s_user =Cache::get($authToken);
}

创建loginApi登录接口,用于生成token并将token存入redis缓存,并根据token失效时间’expiration’ => 60 * 2设置redis值的失效时间,因为sanctum是以分钟为单位,redis是以秒为单位需要乘60换算

public function loginApi(Request $request)
{
$username = $request->post(‘username’);
$password = $request->post(‘password’);

    $user = UserModel::where(['username' => $username, 'password' => md5($password)])->first();
    if (!$user) {
        return ['msg' => '该用户不存在'];
    }

    //1、删除api_personal_access_tokens表历史token信息,实现单点登录
    $user->tokens()->delete();
    //2、令牌创建后,应该立即向用户展示这个纯文本值
    $token = $user->createToken('login-token')->plainTextToken;
    //3、将token存入redis缓存,并根据token失效时间'expiration' => 60 * 2设置redis值的失效时间,因为sanctum是以分钟为单位,redis是以秒为单位需要乘60换算
    $minutes = config('sanctum.expiration');
    $token = explode('|',$token);
    Cache::put($token[1], $user, $minutes * 60);
    return ['data' => ['userinfo' => $user, 'token' => $token[1]]];
}

//获取通过header头传递的Bearer token从缓存中获取用户信息
public function userInfoApi()
{
return $this->s_user;
}

2、UserModel模型

<?php

namespace App\Model;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class UserModel extends Authenticatable
{
use HasApiTokens;

const CREATED_AT = 'create_time';
const UPDATED_AT= 'update_time';
protected $table = 'user';
protected $fillable = [
    'username','password','head_url','admin','is_delete','status'
];

}

3、路由使用
在路由加入auth:sanctum保护路由,指定哪些接口访问需要使用到token验证的

Route::group([‘namespace’ => ‘Test’, ‘prefix’ => ‘test’], function () {
Route::any(‘login’, ‘IndexController@loginApi’);
#用中间件做token验证,放入一下的路由都需要通过token验证
Route::group([‘middleware’=>’auth:sanctum’], function (){
/Route::any(‘userinfo’, function(Request $request){ //return $request->server(); //$user = \App\Model\UserModel::first(); //return $user; });/
Route::any(‘userinfo’, ‘IndexController@userInfoApi’);
});
});

4、展示
a、生成token签名

b、通过签名访问用户信息接口

或者

c、通过redis服务端查看存入的token信息

安装 catfan/medoo扩展
官方使用文档:
https://medoo.lvtao.net/1.2/doc.collaboration.php

cd /usr/local/nginx/html/laravel/
composer require catfan/medoo

使用medoo库:
1、配置bootstrap/app.php

在bootstrap/app.php中注册

use Illuminate\Support\Facades\Config;
use Medoo\Medoo;

// Register as database
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(‘medoo’, function () {
$config = Config::get(‘database.connections.mysql’);
return new Medoo([
‘database_type’ => $config[‘driver’],
‘database_name’ => $config[‘database’],
‘server’ => $config[‘host’],
‘charset’ => $config[‘charset’],
‘port’ => $config[‘port’],
‘prefix’ => $config[‘prefix’],
‘username’ => $config[‘username’],
‘password’ => $config[‘password’],
]);
});

2、配置.env下的数据库和redis配置

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=log
CACHE_DRIVER=redis
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=123456
REDIS_PORT=6379

3、配置config/database.php数据库前缀配置

‘prefix’ => ‘api_’,

测试medoo查询数据库
在routes/api.php写入查询路由

Route::any(‘/medoo’, function(){
$arr = app(‘medoo’)->select(‘user’,’*’);
return $arr;
});

实例:medoo实现分页查询接口
public function pageApi(Request $request)
{
$page = $request->post(‘page’, 1);
$pageSize = $request->post(‘page_size’, 10);

    $param = $request->post();

    $where = [];
    $where['is_delete'] = 0;

    if (!empty($param['username'])) {
        $where['username[~]'] = $param['username'];
    }

    if (!empty($param['status']) && in_array($param['status'], [1, 2])) {
        $where['status'] = $param['status'];
    }

    if (isset($param['admin']) && in_array($param['admin'], [0, 1])) {
        $where['admin'] = $param['admin'];
    }

    $total = $this->medoo->count('user', 'id', $where);
    if ($total == 0) {
        return ['total' => 0, 'data' => []];
    }

    $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
    $where['ORDER'] = ['id' => 'DESC'];

    $data = $this->medoo->select('user', ['id','username', 'password', 'head_url', 'status'], $where);

    return ['total' => $total, 'data' => $data];
}

数据库表结构
CREATE TABLE api_user (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
username varchar(20) NOT NULL,
password varchar(50) NOT NULL,
head_url char(150) NOT NULL COMMENT ‘头像’,
admin tinyint(4) NOT NULL DEFAULT ‘0’,
time int(11) unsigned NOT NULL,
is_delete tinyint(3) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘0:未删除,1:已删除’,
status tinyint(3) unsigned NOT NULL DEFAULT ‘1’ COMMENT ‘状态 1:启用, 2:禁用’,
PRIMARY KEY (id) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2024 年 3 月
 123
45678910
11121314151617
18192021222324
25262728293031
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
手把手教你用AI 10分钟生成一个APP!零基础也能搞定

手把手教你用AI 10分钟生成一个APP!零基础也能搞定

今日,我将向大家展示DeepSeek的全新玩法——从零开始,利用AI创建一个完整的应用程序。借助DeepSee...
开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二! 西风 2026-01-08 19:02:20 来源:...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
老外对屏狂拍!海信全新一代RGB-Mini LED电视亮相轰动CES2026

老外对屏狂拍!海信全新一代RGB-Mini LED电视亮相轰动CES2026

老外对屏狂拍!海信全新一代RGB-Mini LED电视亮相轰动CES2026 量子位的朋友们 2026-01-...
三赴CES,睿尔曼以三大底层能力构建全球化具身智能新基建

三赴CES,睿尔曼以三大底层能力构建全球化具身智能新基建

三赴CES,睿尔曼以三大底层能力构建全球化具身智能新基建 十三 2026-01-07 14:07:17 来源:...
刚开年,马斯克就到账了200亿美金!

刚开年,马斯克就到账了200亿美金!

Failed to fetch content Read More 
首家央企AI独角兽浮出水面!背靠自研大模型,4家国家队资本背书

首家央企AI独角兽浮出水面!背靠自研大模型,4家国家队资本背书

首家央企AI独角兽浮出水面!背靠自研大模型,4家国家队资本背书 Jay 2026-01-07 15:24:04...
8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队

8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队

8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队 思邈 2026-01-0...