You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.1.0如何实现IP白名单?升级后旧方案失效

Spring Boot 3.1.0 配置IP白名单替代方案

Spring Security 6.x(对应Spring Boot 3.x)弃用了WebSecurityConfigurerAdapter,改用基于组件的SecurityFilterChain配置方式。以下是适配你原有IP白名单逻辑的完整配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 配置请求授权规则
                .authorizeHttpRequests(auth -> auth
                        // 允许指定IP访问所有路径
                        .requestMatchers("/**").hasIpAddress("192.0.0.1")
                        // 拒绝所有其他请求(和原有逻辑保持一致)
                        .anyRequest().denyAll()
                )
                // 禁用CSRF防护,和原有配置匹配
                .csrf(csrf -> csrf.disable())
                .build();
    }
}

关键调整说明

  • 用authorizeHttpRequests替代旧版的authorizeRequests,这是Spring Security 6的新API
  • 用requestMatchers替代antMatchers,用于匹配请求路径
  • hasIpAddress方法保留,用来指定允许访问的单个IP;如果需要多个IP或IP段,可以用hasAnyIpAddress:
    .requestMatchers("/**").hasAnyIpAddress("192.0.0.1", "10.0.0.0/24")
    
  • 原有配置中仅允许指定IP访问所有路径,因此用anyRequest().denyAll()确保其他IP无法访问任何资源,和旧逻辑对齐
  • 通过csrf(csrf -> csrf.disable())禁用CSRF,保持和原有配置一致

内容的提问来源于stack exchange,提问作者Sarvesh H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:16:12