点击查看代码
@Component
@Slf4j
@RequiredArgsConstructor
public class CustomFilter extends OncePerRequestFilter {
private final ObjectMapper objectMapper;
/**
* 指定要放行的接口路径
*/
private static final String[] ALLOWED_PATHS = {
"/a/b",
"/a/c"
};
/**
* 需要放行的接口层
*/
private static final String[] ALLOWED_CONTROLLER = {
"/b",
"/c"
};
@Override
protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) throws ServletException, IOException {
String path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()).replaceAll("/+$", "");
// 属于指定的放行路径吗
boolean a = Arrays.asList(ALLOWED_PATHS).contains(path);
// 属于指定的接口层吗
boolean b = Arrays.stream(ALLOWED_CONTROLLER).anyMatch(path::startsWith);
if (!a && !b) {
// 不属于,需要进行鉴权
String ipAddress = TokenDomain.getCurrentIpAddress();
try {
TokenDomain.verifyToken();
} catch (Exception e) {
// 日志输出非法请求ip
log.error(String.format("IP地址【%s】发起了非法请求", ipAddress), e);
// 提示View
warning(httpServletResponse);
// 停止执行后续过滤器和控制器方法
return;
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
/**
* 提示访问者,请求失败的原因
*/
private void warning(ServletResponse response) throws IOException {
// 设置响应类型
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
// 设置字符集
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
// 失败响应对象
Response<String> no = Response.fail(HttpStatus.FORBIDDEN.value(), "身份认证失败,请登录");
// 转json
String errorJson = objectMapper.writeValueAsString(no);
// 写入ServletResponse
response.getWriter().write(errorJson);
}
}
此过滤器适用于接入其他系统登录的jwtToken校验,不同系统对于jwtToken的生成方式不同,因此校验实现也有差异,获取jwtToken和解析jwtToken的具体代码贴出来也就没有实际意义了
点击查看代码
public static void verifyToken() {
String token = getToken();
// 缺失令牌
Assert.notNull(token, "缺失令牌");
Claims claims = parse(token);
// 令牌过期
Assert.isTrue(claims.getExpiration().after(new Date()), "令牌过期");
}