【发布时间】:2020-05-30 16:55:47
【问题描述】:
我已经使用 Spring Security 实现了一个过滤器来检查 IP 地址白名单。 它可以工作,但是如果我在 doFilter 方法中抛出错误,则该 throw 被调用 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 次 Throw。 所以我开始明白为什么了,看看日志:
第一次投掷
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
第三次投掷:
[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]
感谢您的帮助!
【问题讨论】:
标签: java spring security servlets filter