Laravel JWT 扩展的讨论没有结论:php
https://github.com/tymondesigns/jwt-auth/issues/186git
本身整的,整合jwt.auth和jwt.refresh的代码,作出了一个新的middlewaregithub
<?php /* * This file is part of jwt-auth. * * (c) Sean Tymon <tymon148@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Http\Middleware; use Tymon\JWTAuth\Middleware\BaseMiddleware; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; class APIAuthenticate extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, \Closure $next) { $jwtAuth = $this->auth->setRequest($request); if (! $token = $jwtAuth->getToken()) { return $this->respond('tymon.jwt.absent', 'token_not_provided', 400); } try { $user = $this->auth->authenticate($token); } catch (TokenExpiredException $e) { try { $newToken = $jwtAuth->parseToken()->refresh(); $user = $this->auth->authenticate($newToken); if (! $user) { return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404); } $this->events->fire('tymon.jwt.valid', $user); $response = $next($request); $response->headers->set('Authorization', 'Bearer '.$newToken); return $response; } catch (TokenExpiredException $e) { return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]); } catch (JWTException $e) { return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]); } } catch (JWTException $e) { return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]); } if (! $user) { return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404); } $this->events->fire('tymon.jwt.valid', $user); return $next($request); } }
其实就是将jwt.auth和jwt.refresh的代码进行整合,将该middleware做为api接口的认证中间件就能够了。api
可是有一个要注意的:ide
之后获取当前用户的方法须要纠正一下:this
// 文档里的方式 $user = JWTAuth::parseToken()->authenticate();
// 新的方式spa
$user = JWTAuth::authenticate(JWTAuth::getToken());code
即只能获取JWTAuth当前的token(可能已经被更新过的),不能再从request里解析token(parseToken 请求带过来的,可能被更新了)orm
新的方式可能从语义上不太直观,能够考虑再封装一下,自由发挥。。。jwt
==========================================================
必须记得,请求放回的结果里须要检查 Header是否有 Authorization 字段,有的话必须更新本地的token