12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <?php
- namespace App\Http\Middleware;
- use Auth;
- use Closure;
- use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
- use Tymon\JWTAuth\Exceptions\TokenInvalidException;
- use Tymon\JWTAuth\Exceptions\TokenExpiredException;
- use Tymon\JWTAuth\Exceptions\JWTException;
- use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
- use Illuminate\Support\Facades\Log;
- class CheckTokenMiddleware extends BaseMiddleware
- {
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- // 检查此次请求中是否带有 token,如果没有则抛出异常。
- try{
- $this->checkForToken($request);
- }catch (\Exception $exception){
- return response()->json([
- 'code'=>40021,
- 'msg'=>'没有携带token',
- ]);
- }
- // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常
- try {
- // 检测用户的登录状态,如果正常则通过
- if ($this->auth->parseToken()->authenticate()) {
- return $next($request);
- }
- return response()->json([
- 'code'=>50000,
- 'msg'=>'未登录',
- ]);
- } catch (TokenExpiredException $exception) {
- try {
- return response()->json([
- 'code'=>50000,
- 'msg'=>'token已过期',
- ]);
- } catch (JWTException $exception) {
- return response()->json([
- 'code'=>50000,
- 'msg'=>'token已失效,请重新登陆',
- ]);
- }
- } catch (TokenInvalidException $exception) {
- return response()->json([
- 'code'=>50000,
- 'msg'=>'token无效',
- ]);
- }
- }
- }
|