Spring Security 6中/public端点匿名访问配置失效,返回401问题
问题排查与解决
你的配置不生效最核心的原因是**filterChain方法缺少@Bean注解**——Spring无法识别并加载这个自定义的安全过滤链,导致系统使用了Spring Security的默认规则(所有请求都需要认证),所以访问/public才会返回401。
修改后的正确配置
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean // 必须添加这个注解,让Spring管理该Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(a -> a.requestMatchers("/public").permitAll() .anyRequest().authenticated() ); return http.build(); } }
额外排查点(如果添加@Bean后仍有问题)
- 确认请求路径完全匹配:如果你的实际请求是
/public/(带尾部斜杠),可以把匹配规则改成requestMatchers("/public", "/public/"),或者使用pathMatchers("/public/**")来匹配所有以/public开头的路径。 - 检查是否存在其他
@Configuration标注的安全配置类,可能覆盖了当前配置。 - 验证是否有自定义的认证过滤器优先级过高,提前拦截了请求。
内容的提问来源于stack exchange,提问作者Denis_54213213
相关产品推荐
相关产品推荐

