Auth.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2021 勾股工作室
  4. * @license https://opensource.org/licenses/Apache-2.0
  5. * @link https://www.gougucms.com
  6. */
  7. namespace app\api\middleware;
  8. use Firebase\JWT\JWT;
  9. use Firebase\JWT\Key;
  10. use think\facade\Request;
  11. use think\Response;
  12. class Auth
  13. {
  14. public function handle($request, \Closure $next)
  15. {
  16. $token = Request::header('Token');
  17. if ($token) {
  18. if (count(explode('.', $token)) != 3) {
  19. return json(['code'=>404,'msg'=>'非法请求']);
  20. }
  21. $config = get_system_config('token');
  22. //var_dump($config);exit;
  23. try {
  24. JWT::$leeway = 60;//当前时间减去60,把时间留点余地
  25. $decoded = JWT::decode($token, new Key($config['secrect'], 'HS256')); //HS256方式,这里要和签发的时候对应
  26. //return (array)$decoded;
  27. $decoded_array = json_decode(json_encode($decoded),TRUE);
  28. $jwt_data = $decoded_array['data'];
  29. //$request->uid = $jwt_data['userid'];
  30. define('JWT_UID', $jwt_data['userid']);
  31. $response = $next($request);
  32. return $response;
  33. //return $next($request);
  34. } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
  35. return json(['code'=>403,'msg'=>'签名错误']);
  36. }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
  37. return json(['code'=>401,'msg'=>'token失效']);
  38. }catch(\Firebase\JWT\ExpiredException $e) { // token过期
  39. return json(['code'=>401,'msg'=>'token已过期']);
  40. }catch(Exception $e) { //其他错误
  41. return json(['code'=>404,'msg'=>'非法请求']);
  42. }catch(\UnexpectedValueException $e) { //其他错误
  43. return json(['code'=>404,'msg'=>'非法请求']);
  44. } catch(\DomainException $e) { //其他错误
  45. return json(['code'=>404,'msg'=>'非法请求']);
  46. }
  47. } else {
  48. return json(['code'=>404,'msg'=>'token不能为空']);
  49. }
  50. return $next($request);
  51. }
  52. }