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

Spring Boot Security 3.0 公开接口配置异常,调用返回401求助

问题排查与解决方案

常见配置错误及修复方式

1. 规则顺序错误(最可能原因)

Spring Security的授权规则是从上到下匹配,匹配到即停止执行后续规则。如果你把denyAll放在了permitAll前面,所有请求会先被拒绝,包括/public接口。

错误配置示例:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .anyRequest().denyAll() // 先匹配所有请求,后续规则失效
            .requestMatchers(HttpMethod.GET, "/public").permitAll()
            .requestMatchers(HttpMethod.GET, "/private").authenticated()
        )
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

修复后配置:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers(HttpMethod.GET, "/public").permitAll() // 优先放行/public
            .requestMatchers(HttpMethod.GET, "/private").authenticated()
            .anyRequest().denyAll() // 最后拦截其余请求
        )
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

2. 请求路径匹配不精确

  • 检查Controller的映射路径是否和配置完全一致:比如Controller里是@GetMapping("/public/")(带尾斜杠),但请求的是/public,或者配置时写错了路径(比如大小写错误)。
  • 如果项目设置了server.servlet.context-path,请求时需要加上上下文路径,比如上下文路径为/demo,则请求地址应为http://localhost:8080/demo/public。

3. 配置类未被正确扫描

确保你的Security配置类添加了@Configuration注解,且所在包被Spring Boot的组件扫描范围覆盖。

4. 额外拦截规则干扰

临时关闭CSRF防护测试(生产环境按需开启),确认是否是CSRF导致的拦截:

http.csrf(csrf -> csrf.disable());

5. 控制器映射验证

检查Controller代码是否正确:

@RestController
public class HelloController {
    @GetMapping("/public")
    public String publicHello() {
        return "Public Content";
    }

    @GetMapping("/private")
    public String privateHello() {
        return "Private Content";
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:10:55