html调用jwt,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;

}

}

5f3e8a5c261345295b12c33f440c87cc.png

在路由文件中使用中间件Route::rule('index', 'Index/list')->middleware([\app\middleware\MenberApi::class,\app\middleware\menber::class]);

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

a3b531eb6c31847b407fc7b0dc2c4cb4.png

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值