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

Spring Boot 2.6.6升级至3.1.2后Spring Security配置异常求助

Spring Boot 3.1.x Spring Security 配置修正方案

原新版本配置的核心问题

  • 无效的RequestMatcher嵌套:第一个authorizeHttpRequests中使用new AntPathRequestMatcher(new AntPathRequestMatcher("/**"))的嵌套写法,导致请求匹配逻辑异常。
  • 重复配置块调用:多次调用authorizeHttpRequests和exceptionHandling,容易引发规则优先级混乱,不符合新版本链式配置规范。
  • 未指定全局请求范围:旧版本的antMatcher("/**")对应新版本的securityMatcher("/**"),未设置会导致过滤器链无法覆盖所有请求。

修正后的完整配置

SecurityFilterChain 配置

@Bean
public SecurityFilterChain springFilterChain(HttpSecurity http) throws Exception {
    return http
            // 对应旧版本antMatcher("/**"),指定过滤器链处理所有请求
            .securityMatcher("/**")
            // 统一配置异常处理逻辑
            .exceptionHandling(exceptions -> exceptions
                    .authenticationEntryPoint(forbiddenEntryPoint())
                    .accessDeniedHandler(accessDeniedHandler())
            )
            // 统一配置授权规则
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers(
                            "/**/index*",
                            "/**/logout/",
                            "/**/logoutApp",
                            "/rest/getversion*",
                            "/rest/dologin/*",
                            "/rest/menu*",
                            "/rest/getScript*",
                            "/rest/**",
                            "/waveinventoryservice/**"
                    ).permitAll()
                    .requestMatchers("/rest/saveTodo*").hasRole("ADMIN")
                    .anyRequest().denyAll() // 替代requestMatchers("/**").denyAll(),更符合新版规范
            )
            // 保持旧版本的过滤器位置
            .addFilterAt(preAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            // 禁用csrf和headers,与旧版本一致
            .csrf(CsrfConfigurer::disable)
            .headers(HeadersConfigurer::disable)
            .build();
}

WebSecurityCustomizer 配置

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web.ignoring()
            // 直接传入字符串路径,Spring Security自动转换为RequestMatcher
            .requestMatchers(
                    "/**/*.png*", "/**/*.js*", "/**/*.jpg*", "/**/*.svg*", "/**/*.ico*",
                    "/**/*.css*", "/**/login*", "/**/*.woff*", "/**/*.ttf*", "/**/*.eot*"
            );
}

关键修正说明

  1. securityMatcher("/**"):明确过滤器链处理所有请求,与旧版本antMatcher("/**")功能完全一致,确保所有请求都经过该安全配置。
  2. 合并配置块:将异常处理的两个逻辑合并到同一个exceptionHandling块中,避免重复调用导致的逻辑冲突。
  3. 简化写法:直接使用字符串路径作为requestMatchers参数,无需手动创建AntPathRequestMatcher;用anyRequest().denyAll()替代冗余的requestMatchers("/**").denyAll()。
  4. 修复匹配逻辑:移除无效的AntPathRequestMatcher嵌套,确保请求匹配规则正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:55:55