| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace app\api\middleware;
- use Lettered\Support\Exceptions\TokenException;
- use thans\jwt\exception\JWTException;
- use thans\jwt\exception\TokenExpiredException;
- use thans\jwt\facade\JWTAuth;
- use think\facade\Middleware;
- class JWTAuthMiddleware extends Middleware
- {
- /**
- * 实现方法
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/3/10 19:48
- *
- * @param $request
- * @param \Closure $next
- * @return mixed
- * @throws TokenException
- */
- public function handle($request, \Closure $next)
- {
- try {
- // JWT登录鉴权
- JWTAuth::auth();
- }catch (JWTException $e){
- // Token过期刷新
- if ($e instanceof TokenExpiredException){
- try {
- JWTAuth::setRefresh();
- return $this->setAuthentication($next($request));
- }catch (TokenExpiredException $e){
- throw new TokenException([
- 'errmsg' => 'Unauthorized:Request token denied!'
- ]);
- }
- }
- throw new TokenException([
- 'errmsg' => 'Unauthorized:Request denied!'
- ]);
- }
- return $next($request);
- }
- /**
- * 刷新token返回头部
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/3/10 19:49
- *
- * @param $response
- * @param null $token
- * @return mixed
- */
- protected function setAuthentication($response, $token = null)
- {
- $token = $token ?: JWTAuth::refresh();
- JWTAuth::setToken($token);
- return $response->header(['Authorization' => 'Bearer ' . $token]);
- }
- }
|