Spring Boot 6.1+中IP白名单配置无效的问题排查求助
Spring Boot 6.1+ 中IP白名单不生效的问题修复
问题根源
你的IP白名单规则未生效,核心原因有两个:
- 授权规则顺序覆盖:代码末尾的
authorize.requestMatchers(new AntPathRequestMatcher("/rest/**")).permitAll()会匹配所有/rest/**路径的请求,直接跳过前面的IP校验规则——Spring Security的授权规则是从上到下匹配,匹配即停止,这条规则会完全覆盖你之前的IP限制。 - IP测试值不匹配:你用
localhost测试时,实际请求IP是127.0.0.1而非配置的11.11.11.11,这也会导致测试时感觉规则未触发,但这是次要问题。
修复方案
调整授权规则顺序,移除全局允许/rest/**的规则,优先校验IP白名单,再拒绝未通过校验的/rest/**请求:
@EnableWebSecurity @Configuration public class SecurityConfiguration extends VaadinWebSecurity { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); // 注意:BCryptPasswordSimpleEncoder并非Spring官方实现,建议使用BCryptPasswordEncoder } // 自定义路径+IP组合匹配器 private RequestMatcher restIpWhitelistMatcher(String allowedIp) { return request -> { AntPathRequestMatcher pathMatcher = new AntPathRequestMatcher("/rest/**"); IpAddressMatcher ipMatcher = new IpAddressMatcher(allowedIp); return pathMatcher.matches(request) && ipMatcher.matches(request); }; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> { // 1. 允许指定IP访问/rest/** authorize.requestMatchers(restIpWhitelistMatcher("11.11.11.11")).permitAll(); // 2. 拒绝其他未通过IP校验的/rest/**请求 authorize.requestMatchers(new AntPathRequestMatcher("/rest/**")).denyAll(); // 3. 静态资源允许匿名访问 authorize.requestMatchers(new AntPathRequestMatcher("/images/*.png")).permitAll(); authorize.requestMatchers(new AntPathRequestMatcher("/line-awesome/**/*.svg")).permitAll(); // 4. 其他所有请求需要认证 authorize.anyRequest().authenticated(); }); http.csrf(csrf -> csrf.ignoringRequestMatchers(new AntPathRequestMatcher("/rest/**"))); super.configure(http); setLoginView(http, LoginView.class); } }
关键说明
- 规则顺序:必须先配置IP白名单允许规则,再配置拒绝其他
/rest/**请求的规则,确保IP校验优先执行。 - IP测试:本地测试时,将
allowedIp改为127.0.0.1或0:0:0:0:0:0:0:1(IPv6),就能看到非白名单IP被拒绝的效果。 - 密码编码器:替换
BCryptPasswordSimpleEncoder为Spring官方的BCryptPasswordEncoder,避免潜在的实现问题。 - Vaadin兼容性:
super.configure(http)会加载Vaadin的默认安全规则,确保自定义规则在其之前配置,保证优先级。
测试验证
用Postman发送请求:
- 当请求IP在白名单内时,返回200;
- 当请求IP不在白名单内时,返回403 Forbidden,IP限制生效。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

