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

如何将Spring Security配置方法升级至最新Spring Boot Security版本

Spring Boot Security 6+ 版本 SecurityFilterChain 配置升级

你的原配置中使用了Spring Security 5.x及以前的废弃API,以下是适配最新Spring Boot Security(6.x+)的升级版本:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults())
        .csrf(csrf -> csrf.disable())
        .exceptionHandling(exceptions -> exceptions
            .authenticationEntryPoint(authEntryPointJwt)
        )
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/auth/**", "/api/test/**").permitAll()
            .anyRequest().authenticated()
        )
        .addFilterBefore(authTokenFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

关键变更说明

  • 废弃API替换:
    • 用authorizeHttpRequests()替代旧的authorizeRequests(),这是6.x版本授权规则配置的新入口
    • 用requestMatchers()替代旧的antMatchers(),两者功能一致,但属于新的请求匹配API体系
  • 代码风格优化:
    • 使用lambda表达式替代频繁的.and()调用,让配置结构更清晰,符合Spring Security 6.x推荐的写法
    • cors()方法可以通过Customizer.withDefaults()快速启用默认CORS配置,如果需要自定义CORS规则,可替换为:
      .cors(cors -> cors.configurationSource(yourCustomCorsSource))
      
  • 保留原有核心逻辑:
    CSRF禁用、无状态会话、JWT认证入口点、自定义过滤器的配置逻辑完全保留,确保原有功能不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:07