1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
@Slf4j @Component @RequiredArgsConstructor public class JwtInterceptor implements HandlerInterceptor{ private final JwtProperties jwtProperties;
@Override public boolean preHandle( @NonNull HttpServletRequest request, // 请求 @NonNull HttpServletResponse response, // 响应 @NonNull Object handler) { String token = request.getHeader(jwtProperties.getTokenName()); try { var claims = JwtUtils.parseJWT(token, jwtProperties.getKey()); BaseContext.setCurrentId(Long.valueOf(claims.get("id").toString())); return true; } catch (SignatureVerificationException e) { throw new UnauthorizedException("无效签名"); } catch (TokenExpiredException e) { throw new UnauthorizedException("token过期"); } catch (AlgorithmMismatchException e) { throw new UnauthorizedException("token算法不一致"); } catch (SignatureException e) { throw new ForbiddenException("签名错误"); } catch (Exception e) { throw new ServerErrorException("未知 jwt 拦截错误 " + e.getMessage()); } } }
|