Auth.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------------------------------
  4. * GouGuOPEN [ 左手研发,右手开源,未来可期!]
  5. +-----------------------------------------------------------------------------------------------
  6. * @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
  7. +-----------------------------------------------------------------------------------------------
  8. * @Licensed 勾股OA,开源且可免费使用,但并不是自由软件,未经授权许可不能去除勾股OA的相关版权信息
  9. +-----------------------------------------------------------------------------------------------
  10. * @Author 勾股工作室 <hdm58@qq.com>
  11. +-----------------------------------------------------------------------------------------------
  12. */
  13. namespace app\api\middleware;
  14. use Firebase\JWT\JWT;
  15. use Firebase\JWT\Key;
  16. use think\facade\Request;
  17. use think\Response;
  18. class Auth
  19. {
  20. public function handle($request, \Closure $next)
  21. {
  22. $token = Request::header('Token');
  23. if ($token) {
  24. if (count(explode('.', $token)) != 3) {
  25. return json(['code'=>404,'msg'=>'非法请求']);
  26. }
  27. $config = get_system_config('token');
  28. //var_dump($config);exit;
  29. try {
  30. JWT::$leeway = 60;//当前时间减去60,把时间留点余地
  31. $decoded = JWT::decode($token, new Key($config['secrect'], 'HS256')); //HS256方式,这里要和签发的时候对应
  32. //return (array)$decoded;
  33. $decoded_array = json_decode(json_encode($decoded),TRUE);
  34. $jwt_data = $decoded_array['data'];
  35. //$request->uid = $jwt_data['userid'];
  36. define('JWT_UID', $jwt_data['userid']);
  37. $response = $next($request);
  38. return $response;
  39. //return $next($request);
  40. } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
  41. return json(['code'=>403,'msg'=>'签名错误']);
  42. }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
  43. return json(['code'=>401,'msg'=>'token失效']);
  44. }catch(\Firebase\JWT\ExpiredException $e) { // token过期
  45. return json(['code'=>401,'msg'=>'token已过期']);
  46. }catch(Exception $e) { //其他错误
  47. return json(['code'=>404,'msg'=>'非法请求']);
  48. }catch(\UnexpectedValueException $e) { //其他错误
  49. return json(['code'=>404,'msg'=>'非法请求']);
  50. } catch(\DomainException $e) { //其他错误
  51. return json(['code'=>404,'msg'=>'非法请求']);
  52. }
  53. } else {
  54. return json(['code'=>404,'msg'=>'token不能为空']);
  55. }
  56. return $next($request);
  57. }
  58. }