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
相关产品推荐
相关产品推荐

