Authenticate.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. /*
  3. * This file is part of jwt-auth.
  4. *
  5. * (c) Sean Tymon <tymon148@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace App\Http\Middleware;
  11. use Closure;
  12. use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
  13. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  14. class Authenticate extends BaseMiddleware
  15. {
  16. /**
  17. * Handle an incoming request.
  18. *
  19. * @param \Illuminate\Http\Request $request
  20. * @param \Closure $next
  21. *
  22. * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
  23. *
  24. * @return mixed
  25. */
  26. public function handle($request, Closure $next)
  27. {
  28. try{
  29. //从请求中获取token并且验证token是否过期 若是不过期则请求到控制器处理业务逻辑 若是过期则进行刷新
  30. $this->authenticate($request);
  31. return $next($request);
  32. }catch (UnauthorizedHttpException $exception){
  33. try {
  34. $token = $this->auth -> refresh();
  35. return $this->setAuthenticationHeader($next($request), $token);
  36. } catch (\Exception $e) {
  37. return ['code'=>401,'msg'=>'token已失效','list'=>[],'count'=>0,'result'=>new \StdClass];
  38. }
  39. }
  40. }
  41. }