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

Spring Boot POST请求出现401错误求助排查

问题排查与解决方案

1. 401 未授权错误原因及修复

你的Spring Security配置中,仅允许/路径无需认证,/api/**路径需要USER角色,其余所有请求都要求认证。而你的POST接口路径/response/postbody不在上述允许范围内,因此被拦截返回401。

修复方式二选一:

方式一:修改Security配置,放行目标路径

更新securityFilterChain方法,添加对/response/**的放行规则:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(auth -> {
                auth.requestMatchers("/", "/response/**").permitAll(); // 新增/response/**路径放行
                auth.requestMatchers("/api/**").hasRole("USER");
                auth.anyRequest().authenticated();
            })
            .httpBasic(Customizer.withDefaults())
            .build();
}

方式二:在curl请求中添加认证信息

使用-u参数传入配置好的用户名和密码:

curl -X POST -u administrator:bullshit123 -H "Content-type: application/json" -d "\"John Smith\"" "http://localhost:8080/response/postbody"

2. 请求体格式错误修复

你设置了Content-type: application/json,但传入的请求体"John Smith"不是合法的JSON字符串(JSON字符串必须被双引号包裹),会导致Spring解析@RequestBody时返回400 Bad Request。需调整请求体格式:

# 转义双引号写法
curl -X POST -u administrator:bullshit123 -H "Content-type: application/json" -d "\"John Smith\"" "http://localhost:8080/response/postbody"

# 单引号包裹写法(更简洁)
curl -X POST -u administrator:bullshit123 -H "Content-type: application/json" -d '"John Smith"' "http://localhost:8080/response/postbody"

验证

修改后重启应用,执行上述curl命令,应返回Hello "John Smith",说明接口正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:17:17