Api.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\middleware;
  4. use app\common\Redis;
  5. use app\common\Request;
  6. use app\common\Token;
  7. use Firebase\JWT\JWT;
  8. use think\Exception;
  9. class Api
  10. {
  11. /**
  12. * 处理请求
  13. * @param $request
  14. * @param \Closure $next
  15. * @return \think\response\Json
  16. */
  17. public function handle($request, \Closure $next)
  18. {
  19. $authorization = $request->header('authorization');
  20. if(!$authorization) {
  21. return error('请求未携带authorization信息');
  22. }
  23. if(count(explode(' ', $authorization)) < 2){
  24. return error('接口认证方式错误');
  25. }
  26. list($type, $token) = explode(' ', $authorization);
  27. if ($type !== 'Bearer') {
  28. return error('接口认证方式需为Bearer');
  29. }
  30. if (!$token) {
  31. return error('尝试获取的authorization信息不存在');
  32. }
  33. $msg = Redis::getRedis()->hGet('check_token_phone','12345678910');
  34. if($token != $msg){
  35. return error('未登陆或token失效,请重新登陆');
  36. }
  37. try {
  38. Token::getTokenValue($token);
  39. } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
  40. return error('令牌签名不正确');
  41. } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
  42. return error('令牌尚未生效',401);
  43. } catch (\Firebase\JWT\ExpiredException $e) { // token过期
  44. return error('令牌已过期,刷新浏览器重试',401);
  45. } catch (Exception $e) { //其他错误
  46. throw new Exception($e->getMessage());
  47. }
  48. return $next($request);
  49. }
  50. }