Spring Boot - 注册过滤器
过滤器
Token 验证过滤器,如果没有携带 Token 说明没有登录,或服务器没有颁发合法的 Token 给客户端。
file:[TokenFilter.java]
public class TokenFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
String token = request.getHeader("Token");
if (token == null) {
R r = new R(500, null, "您没有登陆!");
String json = JSON.toJSONString(r);
response.getWriter().write(json);
} else {
filterChain.doFilter(request, response);
}
}
}
在配置跨域过滤器设置响应头要记得添加 Token,否则从前端过来的请求携带的是其他字段就会被拒绝,出现跨域。如果请求头是其他的字段,如 Authorization,Access-Control-Allow-Headers
就得包含这个字段。
file:[CorsFilter.java]
public class CorsFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Token, Content-Type");
chain.doFilter(request, response);
}
}
配置类
file:[FilterConfig.java]
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new CorsFilter());
bean.addUrlPatterns("/*"); // 匹配的 URL
bean.setOrder(1); // 设置优先级
return bean;
}
@Bean
public FilterRegistrationBean<TokenFilter> authFilter() {
FilterRegistrationBean<TokenFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new TokenFilter());
bean.addUrlPatterns("/api/auth/*"); // 设置需要过滤的 URL 匹配模式
bean.setOrder(2);
return bean;
}
}
多个过滤器之间需要合理地设置执行顺序,就如上两个过滤器,跨域的问题是首要的,所以设置 1,数字越小代表优先级越高。其次,经过 Token 校验过滤器,合法就允许访问,不合法就阻止访问。