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

Spring Boot 2.x.x升级至3.3.0时Security配置报错求助

解决Spring Boot 3.3.0升级后的Security配置废弃警告问题

这是Spring Boot 3.x对应的Spring Security 6.x版本废弃了一批旧API导致的警告,直接按以下方式修改配置类即可解决:

核心修改点

  • 用@EnableMethodSecurity替代旧的@EnableGlobalMethodSecurity(Spring Security 6+推荐写法,功能完全一致)
  • 替换authorizeRequests()为authorizeHttpRequests()
  • 替换antMatchers()为requestMatchers()
  • 移除所有显式的and()调用:新版本HttpSecurity支持直接链式配置模块,无需用and()切换

修改后的完整配置类

import com.connect.bytr.api.constants.BYTRConstants;
import com.connect.bytr.api.filters.AuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;

@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    private final AuthenticationFilter authenticationFilter;

    private final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/configuration/ui",
            "/configuration/security",
            "/webjars/**"
    };

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(AUTH_WHITELIST).permitAll()
                        .anyRequest().authenticated())
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(unauthorizedEntryPoint()))
                .addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() {
        return (request, response, authException) ->
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, BYTRConstants.UNAUTHORIZED);
    }
}

额外说明

  • 新版本采用Lambda风格的配置,每个模块(比如csrf、authorizeHttpRequests)通过传入Lambda表达式来配置,代码更清晰,也避免了旧的and()链式调用的废弃问题
  • @EnableMethodSecurity默认已经开启prePostEnabled = true,如果不需要额外配置,甚至可以直接写@EnableMethodSecurity

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:10:10