限制Spring Boot中Tomcat只能访问特定IP地址

11

我需要限制基于Spring Boot的应用程序中嵌入式Tomcat仅允许来自两个IP地址的连接,而不是允许所有连接。我知道如何在非嵌入式Tomcat中做到这一点,但不知道如何在Spring Boot中配置。各种server.tomcat.*属性似乎没有提供对此的支持。有一个server.address属性可以将本地IP地址绑定,但这并不是我需要的。


1
如果你知道如何在独立容器中完成它,那么在Tomcat中找到API就不难了(可能是“Valve”或“Connector”属性 - 从server.xml文件中很容易看出)。但是客户端很容易伪造他们的IP地址,因此如果安全是您的目标,最好坚持使用其他方法。 - Dave Syer
2个回答

16

在寻找相同解决方案时发现了这个答案。这是在Spring Boot中更准确的实现方式。

@Bean
public FilterRegistrationBean remoteAddressFilter() {

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    RemoteAddrFilter filter = new RemoteAddrFilter();

    filter.setAllow("192.168.0.2");
    filter.setDenyStatus(404);

    filterRegistrationBean.setFilter(filter);
    filterRegistrationBean.addUrlPatterns("/*");

    return filterRegistrationBean;

}

默认的响应状态是403。要将其更改为404,需要添加filter.setDenyStatus(404);

您还可以使用filter.setDeny("192\\.168\\.0\\.2");设置拒绝地址。

Tomcat的RemoteAddressFilter文档


2

如果您想添加多个IP地址,则可以使用Spring Security和自定义身份验证提供程序。 自定义身份验证提供程序配置如下:

@Component
public class CustomIpAuthenticationProvider implements AuthenticationProvider {

   Set<String> whitelist = new HashSet<String>();

    public CustomIpAuthenticationProvider() {
        whitelist.add("103.219.56.22");
        whitelist.add("192.168.2.33");
    }

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {

        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        String userIp = details.getRemoteAddress();

        if(! whitelist.contains(userIp)) {
            throw new BadCredentialsException("Invalid IP Address");
        }
    }
}

以下是Spring Security的配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomIpAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
          .antMatchers("/login").permitAll()
          .anyRequest().authenticated()
          .and().formLogin().permitAll()
          .and().csrf().disable();
    }

}

如果您只想让特定IP地址访问某些特定映射,则Spring Security的配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
          .antMatchers("/login").permitAll()
          .antMatchers("/rockstar/**").hasIpAddress("103.219.55.22")
          .anyRequest().authenticated()
          .and()
          .formLogin().permitAll()
          .and()
          .csrf().disable();
    }
}

1
这是一个很好的答案,但它是一个应用程序IP过滤器,上面的答案是一个容器IP过滤器,这是一个更好的解决方案。 - downvoteit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接