Laravel常用扩展sanctum与medoo的使用

1,005次阅读
没有评论

安装 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
 
评论(没有评论)