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*" ); }
关键修正说明
securityMatcher("/**"):明确过滤器链处理所有请求,与旧版本antMatcher("/**")功能完全一致,确保所有请求都经过该安全配置。- 合并配置块:将异常处理的两个逻辑合并到同一个
exceptionHandling块中,避免重复调用导致的逻辑冲突。 - 简化写法:直接使用字符串路径作为
requestMatchers参数,无需手动创建AntPathRequestMatcher;用anyRequest().denyAll()替代冗余的requestMatchers("/**").denyAll()。 - 修复匹配逻辑:移除无效的
AntPathRequestMatcher嵌套,确保请求匹配规则正常生效。
内容的提问来源于stack exchange,提问作者kindMeetsEvil
相关产品推荐
相关产品推荐

