繁体   English   中英

将使用 java 和 SpringBoot 框架创建的微服务中的一组 ipAdresses 列入黑名单

[英]blacklisting a set of ipAdresses in a microservice created using java and SpringBoot framework

我有一个微服务,旨在询问不同类型和操作系统的设备,但出于一系列原因,我想将少数 IP 列入黑名单。 有没有办法我可以做到这一点?

您是否尝试过使用 HandlerInterceptor 接口?

与 WebMvcConfigurerAdapter 结合使用。 这应该可以完成这项工作。

像这样的东西,这里不是确切的工作代码

//Call after request processing, but before the view is rendered (after controller method call)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);
    List<BlackList> blackLists = blackListDao.findByIp(ip);
    if (blackLists == null || blackLists.size() == 0){
        urlHandle(httpServletRequest, 5000, 10);
    } else {
         //Forced control jump
         modelAndView.setViewName("/errorpage/error.html");
    }
}

BlackListDao class 可以是这样的

@Mapper
public interface BlackListDao {
    //Find records by IP
    List<BlackList> findByIp(String IP);
    //Add record
    int addBlackList(@Param("blackList") BlackList blackList);
}

为 spring MVC 配置拦截器 Webmvcconfigureradapter。

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Bean // inject our interceptor as bean
    public HandlerInterceptor getMyInterceptor(){
    return new URLInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
    //Multiple interceptors form an interceptor chain
    //Addpathpatterns is used to add interception rules. Here we assume that all links after interception / URL
    //Excludepathpatterns user exclusion
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/url/**");
            super.addInterceptors(registry);
}

最好的方法是在HttpFirewall中检查它,它可以在通过FilterChainProxy允许它到 go 之前检查HttpServletRequest是否存在潜在危险。

基本上,您需要覆盖默认的StrictHttpFirewall并添加逻辑以检查请求的源 IP 是否在黑名单中,例如:

public class MyFirewall extends StrictHttpFirewall {

    private Set<String> backlistIPs;

    public MyFirewall(Set<String> backlistIPs){
         this.backlistIPs = backlistIPs;
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        
        String sourceIp = getClientIpAddress(request);

        if(backlistIPs.contains(sourceIp)){
          throw new RequestRejectedException("IP is blacklisted");
        }

        return super.getFirewalledRequest(request);
    }
}

注意:请参阅此处了解如何实现 getClientIpAddress()

然后配置使用它:

@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.httpFirewall(new MyFirewall(Set.of("123.123.123.123" ,"123.123.123.124"));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM