原因
因为jwt如果token验证失败,会返回验证失败,但是因为格式没有被通过配置控制,所以在前后端交互上很麻烦
自定义中间件
创建中间件文件
文件的位置在app/Http/Middleware
,内容如下
<?php namespace App\Http\Middleware; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Closure; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; class authJWT extends BaseMiddleware { public function handle($request, \Closure $next) { if (! $token = $this->auth->setRequest($request)->getToken()) { $this->expreturn(); } try { $user = $this->auth->authenticate($token); } catch (JWTException $e) { $this->expreturn(); $this->events->fire('tymon.jwt.valid', $user); return $next($request); } private function expreturn(){ $response = new Response(); $response->headers->set('Accept', 'application/json'); $response->setContent(json_encode([ 'code'=>401, 'msg'=>'token验证过期', 'data'=>[], ])); $response->setStatusCode(401); $response->send(); exit(); } }
这里可以自定义需要的格式,上面例子仅供参考
替换之前的中间件
app/Http/Kernel.php
// 'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class, 'auth.jwt' => authJWT::class
控制器替换
public function __construct() { // $this->middleware('auth:'.$this->guard); $this->middleware(authJWT::class); $this->user = auth($this->guard)->user(); }
总结
这样就完成了中间件的替换,达到了自定义验证失败格式的目的。
这部分还有优化空间,有时间我会进一步详解。