[英]doFilter method called multiple times when an error is throw in a custom Servlet Filter
我已经实现了一个过滤器来使用 Spring Security 检查 IP 地址白名单。 它有效,但是如果我在 doFilter 方法中抛出错误,则该抛出将被调用 3 次 oO。
我找到了一个带有“return;”的解决方案,但我对此并不满意。 这意味着我必须在不使用 throw 的情况下记录我的错误...
你怎么看,有没有更好的办法? 最佳实践?
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
这是网页配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").permitAll().and()
.addFilterBefore(new CustomIpFilter(),
BasicAuthenticationFilter.class)
.csrf().disable()
.formLogin().disable();
}
}
这是我的过滤器
@Log4j2
@WebFilter
public class CustomIpFilter implements Filter {
Set<String> whitelist = new HashSet<>();
public CustomIpFilter() {
whitelist.add("0:0:0:0:0:0:0:1"); //localhost
whitelist.add("127.0.0.1");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String ipAdress = request.getRemoteAddr();
if (!whitelist.contains(ipAdress)) {
log.error("Unknown IP adress");
/* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
throw new UnknownHostException("Unknown IP adress");*/
return;
}
chain.doFilter(request, response); //Continue
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
用于测试的控制器
@RestController
@RequestMapping(value = "test")
public class LoggerController {
@GetMapping("/go")
public String logsTest() {
System.out.println("ok");
return "Ok";
}
}
我已经尝试过使用“preHandle”方法使用拦截器删除 Spring Security 的相同内容,但我仍然有 3 次投掷。 所以我开始明白为什么,看看日志:
第一次投掷
java.net.UnknownHostException: Unknown IP adress
第二次投掷
[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] threw exception
第 3 次投掷:
[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]
谢谢你的帮助 !
您正在 Servlet 环境中运行。 servlet 规范没有说你应该通过抛出异常来响应错误。 相反,您应该使用 HTTP 状态代码和消息进行响应。 当您抛出异常时,servlet 容器将尽力找出要做什么,但经常会导致 500 Internal Server Error 返回给用户,这是不准确或有帮助的。
仅仅从过滤器返回也不正确,因为您没有在 HTTP 响应中放入任何内容。 同样,您应该在响应中设置适当的状态代码,例如 403 Forbidden,它向调用者指示某些内容未正确配置。
为了回答我的问题,我的过滤器终于按照@rgoers 的解释正常工作了
@Log4j2
@WebFilter
public class CustomIpFilter implements Filter {
private final Set<String> whitelist = new HashSet<>();
private final String unauthorizedIpAddressMessage = "CONNECTION REFUSED: Unauthorized IP address: ";
public CustomIpFilter() {
whitelist.add("0:0:0:0:0:0:0:1"); //localhost
whitelist.add("127.0.0.1");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String ipAddress = request.getRemoteAddr();
if (!isAuthorizedIpAdress(ipAddress)) {
log.error(unauthorizedIpAddressMessage + ipAddress);
setUnauthorizedHttpServletResponse(response, unauthorizedIpAddressMessage + ipAddress);
return;
}
chain.doFilter(request, response); //Continue
}
public void setUnauthorizedHttpServletResponse(ServletResponse response, String message)
throws IOException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.getWriter().write(message);
httpResponse.getWriter().flush();
httpResponse.getWriter().close();
}
public boolean isAuthorizedIpAdress(String ipAddress) {
if (Utils.isElementInSetList(whitelist, ipAddress)) {
return true;
}
return false;
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.