Laravel常用扩展sanctum与medoo的使用

2,117次阅读
没有评论

安装 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、百度等平台型巨头持续布局
文章搜索
热门文章
潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026 Jay 2025-12-22 09...
面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25 鹭羽 2025-12-13 22:37...
钉钉又发新版本!把 AI 搬进每一次对话和会议

钉钉又发新版本!把 AI 搬进每一次对话和会议

钉钉又发新版本!把 AI 搬进每一次对话和会议 梦晨 2025-12-11 15:33:51 来源:量子位 A...
5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级 思邈 2025-12-10 14:28:37 来源:量子位 让更大规...
商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1 十三 2025-12-15 14:13:14 ...
最新评论
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.
热评文章
读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了

读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了

读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了 衡宇 2025-12-10 12:3...
5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级 思邈 2025-12-10 14:28:37 来源:量子位 让更大规...
戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案

戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案

戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案 十三 2025-12-10 1...
九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局

九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局

九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局 量子位的朋友们 2025-12-10 18:...
乐奇Rokid这一年,一路狂飙不回头

乐奇Rokid这一年,一路狂飙不回头

乐奇Rokid这一年,一路狂飙不回头 梦瑶 2025-12-10 20:41:15 来源:量子位 梦瑶 发自 ...