| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace app\http\middleware;
- use Lettered\Support\Exceptions\TokenException;
- use Lettered\Support\Exceptions\UserException;
- use thans\jwt\exception\JWTException;
- use thans\jwt\exception\TokenExpiredException;
- use thans\jwt\facade\JWTAuth;
- use think\facade\Middleware;
- /**
- * 自定义验证类
- * @package app\http\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' => '登录失效'
- ]);
- }
- }
- throw new TokenException([
- 'errmsg' => '请先登录'
- ]);
- }
- 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]);
- }
- }
|