<?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);
}
} 最佳答案