CheckTokenMiddleware.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Auth;
  4. use Closure;
  5. use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
  6. use Tymon\JWTAuth\Exceptions\TokenInvalidException;
  7. use Tymon\JWTAuth\Exceptions\TokenExpiredException;
  8. use Tymon\JWTAuth\Exceptions\JWTException;
  9. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  10. use Illuminate\Support\Facades\Log;
  11. class CheckTokenMiddleware extends BaseMiddleware
  12. {
  13. /**
  14. * Handle an incoming request.
  15. *
  16. * @param \Illuminate\Http\Request $request
  17. * @param \Closure $next
  18. * @return mixed
  19. */
  20. public function handle($request, Closure $next)
  21. {
  22. // 检查此次请求中是否带有 token,如果没有则抛出异常。
  23. try{
  24. $this->checkForToken($request);
  25. }catch (\Exception $exception){
  26. return response()->json([
  27. 'code'=>40021,
  28. 'msg'=>'没有携带token',
  29. ]);
  30. }
  31. // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常
  32. try {
  33. // 检测用户的登录状态,如果正常则通过
  34. if ($this->auth->parseToken()->authenticate()) {
  35. return $next($request);
  36. }
  37. return response()->json([
  38. 'code'=>50000,
  39. 'msg'=>'未登录',
  40. ]);
  41. } catch (TokenExpiredException $exception) {
  42. try {
  43. return response()->json([
  44. 'code'=>50000,
  45. 'msg'=>'token已过期',
  46. ]);
  47. } catch (JWTException $exception) {
  48. return response()->json([
  49. 'code'=>50000,
  50. 'msg'=>'token已失效,请重新登陆',
  51. ]);
  52. }
  53. } catch (TokenInvalidException $exception) {
  54. return response()->json([
  55. 'code'=>50000,
  56. 'msg'=>'token无效',
  57. ]);
  58. }
  59. }
  60. }