如何从Spring Security 5.x迁移至6.1.x?代码迁移遇403错误求助
Spring Security 6.1.x 迁移配置及403问题解决
问题原因
Spring Security 6.x 废弃了authorizeRequests,改用authorizeHttpRequests,并且默认授权逻辑更严格——所有未明确放行的请求都会被拒绝。你之前的配置只放行了/路径,其他请求会被拦截返回403;另外如果写法不规范(比如链式调用错误),也会导致规则不生效。
正确配置示例
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 链式配置授权规则,替代旧的 authorizeRequests http.authorizeHttpRequests(auth -> auth // 放行指定的公开路径 .requestMatchers("/").permitAll() // 其他所有请求需要认证(根据实际需求调整,不需要认证就改成.permitAll()) .anyRequest().authenticated() ); http.cors().and().csrf().disable(); return http.build(); } }
关键注意事项
- 补充需要放行的路径:如果有静态资源(如
/css/**、/js/**)或公开接口(如/api/public/**),直接在requestMatchers里追加:.requestMatchers("/", "/css/**", "/api/public/**").permitAll() - 全局放行(谨慎使用):如果你的应用所有接口都不需要认证,把
.anyRequest().authenticated()替换成.anyRequest().permitAll(),但生产环境务必确认需求后再这么做。 - 检查路径匹配:确保
requestMatchers里的路径和实际请求路径完全匹配,拼写错误或路径遗漏都会导致403。
内容的提问来源于stack exchange,提问作者hermi wael
相关产品推荐
相关产品推荐

