jwt-auth 中间件如何使用 避免踩坑

发表时间:2020-05-13 03:18:24
摘要信息

thinkphp 使用 jwt-auth 做接口权限控制,中间件如何使用 避免踩坑

安装:

composer require thans/tp-jwt-auth

新建中间件

php think make:middleware menber


中间件使用

<?php
declare (strict_types=1);

namespace app\middleware;

use thans\jwt\facade\JWTAuth;
use thans\jwt\exception\JWTException;

class menber
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
$request->key = ['null'];
// print_r($request->header('Authorization'));
try {
$data = JWTAuth::auth();
$request->key = $data;
} catch (JWTException $e) {
print_r($e->getMessage());
}
return $next($request);
}
}

如果是跨域请求,需要自己再创建一个中间件

<?php
declare (strict_types=1);

namespace app\middleware;

class MenberApi
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
/** @var Response $response */
$response = $next($request);

$response->header([
'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,token,uid,Cookie,authorization',
'Access-Control-Allow-Credentials' => 'true'
]);
if (strtoupper($request->method()) == "OPTIONS") {

return $response;
}
return $response;
}
}


在路由文件中使用中间件

Route::rule('index', 'Index/list')->middleware([\app\middleware\MenberApi::class,\app\middleware\menber::class]);

第一个中间件是处理跨域请求,第二个是接口权限控制,下面是接口效果



40% Complete (success)