我需要将基于spring boot的应用程序的嵌入式tomcat限制为特定的ip地址。我希望只允许来自两个ip地址的传入连接,而不是全部。我知道如何在没有运行嵌入式的tomcat中做到这一点,但不知道如何在spring boot中配置它。各种server.tomcat.*属性似乎不提供对此的支持。有一个属性server.address可以让我绑定到本地ip地址,但这不是我需要的。
发布于 2017-06-04 15:56:25
在搜索相同的解决方案时找到了这个答案。这是在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");设置拒绝地址
发布于 2018-12-26 15:54:27
如果您想添加多个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安全配置:
@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();
}
}https://stackoverflow.com/questions/27743840
复制相似问题