基于TP6写了个API的JWT验证中间件,看看有啥缺陷

浏览:2761 发布日期:2020/05/04 分类:ThinkPHP6专区
没有做过API接口,第一次,由于老思想在很多模型基类里面使用了Session之类的东东,模型又是公用的,不想再改动了~TP6的Session其实就是缓存,我就把他当缓存用了~<?php
declare (strict_types = 1);

namespace app\middleware;

use Closure;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Token;
use think\App;
use think\Request;
use think\Response;
use think\Session;
use Lcobucci\JWT\ValidationData;

class ApiSession
{
    /** @var App */
    protected $app;

    /** @var Session */
    protected $session;

    private $tenant_id;
    private $session_id;
    private $host;

    public function __construct(App $app, Session $session)
    {
        $this->app     = $app;
        $this->session = $session;
    }
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure       $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        if($request->header('Authorization')) {
            $token = $request->header('Authorization');
            $signer = new Sha256();
            $publicKey = new Key('file://'.$this->app->getAppPath().'rsa_public_key.crt');
            //解析token
            $token = (new Parser())->parse((string) $token); // Parses from a string
            if($this->checkToken($token) === false)
            {
                return Response::create(['code'=>1,'msg'=>'token失效'],'json');
            }
            if($token->verify($signer,$publicKey))
            {
                $this->session->setId($this->session_id);
                $this->session->init();
                $request->withSession($this->session);
            }
            else
            {
                return Response::create(['code'=>1,'msg'=>'验签失败'],'json');
            }
        }
        else{
            return Response::create(['code'=>1,'msg'=>'未取得有效token'],'json');
        }
        return $next($request);
    }

    private function checkToken(Token $token)
    {
        $this->session_id = $token->getHeader('jti');
        $this->tenant_id = $token->getClaim('aud');
        $this->host = $token->getClaim('iss');
        //验证过期
        $valid = new ValidationData();
        $valid->setIssuer($this->host);
        $valid->setAudience($this->tenant_id);
        $valid->setId($this->session_id);
        return $token->validate($valid);
    }
}
最佳答案
评论() 相关
后面还有条评论,点击查看>>