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

使用GET方法带JWT调用Java REST API时Postman报400错误

问题原因及修复方案

核心问题:参数注解误用

你的getAllWeights方法给Principal参数加了@RequestParam注解,这是错误的。Principal是Spring Security通过安全上下文自动注入的认证对象,并非URL请求参数。加了这个注解后,Spring会强制要求请求携带名为principal的查询参数,但你没传,直接触发400 Bad Request错误。

修复步骤

  1. 修改控制器方法参数,移除@RequestParam注解:
@GetMapping("/all")
public ResponseEntity<List<WeightRecord>> getAllWeights(Principal principal) {
    logger.info("GET /weights/all");
    Long appUserConnectedId = this.getAppUserConnectedId(principal);
    Person personToShow = personRepository.findById(appUserConnectedId).orElseThrow();
    return new ResponseEntity<List<WeightRecord>>(personToShow.getWeightsList(), HttpStatus.OK);
}
  1. 可选优化(简化代码):
    如果你的AppUser是Spring Security的认证用户对象,可以直接用@AuthenticationPrincipal注解获取当前用户,省去手动转换Principal的步骤:
@GetMapping("/all")
public ResponseEntity<List<WeightRecord>> getAllWeights(@AuthenticationPrincipal AppUser currentUser) {
    logger.info("GET /weights/all");
    Person personToShow = personRepository.findById(currentUser.getIdUser()).orElseThrow();
    return new ResponseEntity<List<WeightRecord>>(personToShow.getWeightsList(), HttpStatus.OK);
}
  1. Postman请求验证要点:
  • 请求URL使用http://localhost:7777/weights/all
  • 请求头正确携带JWT令牌,格式为Authorization: Bearer 你的JWT字符串
  • 不要在URL中添加principal参数

额外排查方向

  • 检查JWT令牌是否过期、签名是否有效
  • 确认Spring Security配置已正确启用JWT认证,且/weights/all路径的权限规则配置无误
  • 查看Tomcat日志,获取400错误的具体细节(比如参数缺失提示)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:36:22