JWTAuthMiddleware.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace app\api\middleware;
  3. use Lettered\Support\Exceptions\TokenException;
  4. use thans\jwt\exception\JWTException;
  5. use thans\jwt\exception\TokenExpiredException;
  6. use thans\jwt\facade\JWTAuth;
  7. use think\facade\Middleware;
  8. class JWTAuthMiddleware extends Middleware
  9. {
  10. /**
  11. * 实现方法
  12. *
  13. * @author 许祖兴 < zuxing.xu@lettered.cn>
  14. * @date 2020/3/10 19:48
  15. *
  16. * @param $request
  17. * @param \Closure $next
  18. * @return mixed
  19. * @throws TokenException
  20. */
  21. public function handle($request, \Closure $next)
  22. {
  23. try {
  24. // JWT登录鉴权
  25. JWTAuth::auth();
  26. }catch (JWTException $e){
  27. // Token过期刷新
  28. if ($e instanceof TokenExpiredException){
  29. try {
  30. JWTAuth::setRefresh();
  31. return $this->setAuthentication($next($request));
  32. }catch (TokenExpiredException $e){
  33. throw new TokenException([
  34. 'errmsg' => 'Unauthorized:Request token denied!'
  35. ]);
  36. }
  37. }
  38. throw new TokenException([
  39. 'errmsg' => 'Unauthorized:Request denied!'
  40. ]);
  41. }
  42. return $next($request);
  43. }
  44. /**
  45. * 刷新token返回头部
  46. *
  47. * @author 许祖兴 < zuxing.xu@lettered.cn>
  48. * @date 2020/3/10 19:49
  49. *
  50. * @param $response
  51. * @param null $token
  52. * @return mixed
  53. */
  54. protected function setAuthentication($response, $token = null)
  55. {
  56. $token = $token ?: JWTAuth::refresh();
  57. JWTAuth::setToken($token);
  58. return $response->header(['Authorization' => 'Bearer ' . $token]);
  59. }
  60. }