thinkphp6整合jwt

  • composer安装jwt包
  • 创建密钥
php think jwt:create
  • 使用方式:

    对于需要验证的路由或者模块添加中间件:

thans\jwt\middleware\JWTAuth::class,
  • 示例:
$token = JWTAuth::builder(['uid' => 1]);//参数为用户认证的信息,请自行添加

JWTAuth::auth();//token验证

JWTAuth::refresh();//刷新token,会将旧token加入黑名单

$tokenStr = JWTAuth::token()->get(); //可以获取请求中的完整token字符串

$payload = JWTAuth::auth(); //可验证token, 并获取token中的payload部分
$uid = $payload['uid']->getValue(); //可以继而获取payload里自定义的字段,比如uid

拉黑Token   JWTAuth::invalidate($token);
查询Token是否黑名单   JWTAuth::validate($token);
  • CheckLogin.php
<?php

declare (strict_types=1);

namespace app\common\middleware;

use thans\jwt\facade\JWTAuth;
use think\exception\HttpResponseException;
use think\Response;

class CheckLogin extends JWTAuth
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {
            // 获取Token
            $token = request()->header("Authorization");
            if ($token && strpos($token, 'Bearer ') !== false) {
                // JWT解密token
                $payload = JWTAuth::auth(); //可验证token, 并获取token中的payload部分
                if (!$payload){
                    $this->result(401,"请登录");
                }
                $userId = $payload['user_id']->getValue(); //可以继而获取payload里自定义的字段,比如uid
                if (!$userId) {
                    $this->result(401,"请登录");
                }
                $request->userId = $userId;
            } else {
                $this->result(401,"请登录");
            }
        } catch (\Exception $e) {
            $this->result(401,'请登录');
//            return json($e->getMessage());
        }

        return $next($request);
    }


    /**
     * 返回封装后的API数据到客户端
     * @param  mixed   $data 要返回的数据
     * @param  integer $code 返回的code
     * @param  mixed   $msg 提示信息
     * @param  string  $type 返回数据格式
     * @param  array   $header 发送的Header信息
     * @return Response
     */
    protected function result(int $code, $msg, $data = [], string $type = '', array $header = []): Response
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
            'time' => time()
        ];

        $type     = $type ?: 'json';
        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }


}
  • app/config/middleware.php
<?php
// 中间件配置
return [
    // 别名或分组
    'alias'    => [
        'auth' => \app\common\middleware\CheckLogin::class,
    ],
    // 优先级设置,此数组中的中间件会按照数组中的顺序优先执行
    'priority' => [],
];
  • controller
class Login extends ApiController
{

    /**
     * 控制器中间件
     * 注册控制器中间件
     * [
     *      //对所有方法有效
     *      'auth',
     *      //仅对hello方法和world方法有效
     *      'check' => ['only' => ['hello', 'world']],
     *      //仅对create方法和save方法无效
     *      'check' => ['except' => ['create', 'save']],
     * ]
     * @var array
     */
    protected $middleware = [
        'auth' => ['except' => ['login','logout']],
    ];
}
© 版权声明
THE END
喜欢就支持一下吧
分享