JWTAuthMiddleware.php 1.9 KB

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