123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- declare (strict_types = 1);
- namespace app\middleware;
- use app\common\Redis;
- use app\common\Request;
- use app\common\Token;
- use Firebase\JWT\JWT;
- use think\Exception;
- class Api
- {
- /**
- * 处理请求
- * @param $request
- * @param \Closure $next
- * @return \think\response\Json
- */
- public function handle($request, \Closure $next)
- {
- $authorization = $request->header('authorization');
- if(!$authorization) {
- return error('请求未携带authorization信息');
- }
- if(count(explode(' ', $authorization)) < 2){
- return error('接口认证方式错误');
- }
- list($type, $token) = explode(' ', $authorization);
- if ($type !== 'Bearer') {
- return error('接口认证方式需为Bearer');
- }
- if (!$token) {
- return error('尝试获取的authorization信息不存在');
- }
- $msg = Redis::getRedis()->hGet('check_token_phone','12345678910');
- if($token != $msg){
- return error('未登陆或token失效,请重新登陆');
- }
- try {
- Token::getTokenValue($token);
- } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
- return error('令牌签名不正确');
- } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
- return error('令牌尚未生效',401);
- } catch (\Firebase\JWT\ExpiredException $e) { // token过期
- return error('令牌已过期,刷新浏览器重试',401);
- } catch (Exception $e) { //其他错误
- throw new Exception($e->getMessage());
- }
- return $next($request);
- }
- }
|