使用GET方法带JWT调用Java REST API时Postman报400错误
问题原因及修复方案
核心问题:参数注解误用
你的getAllWeights方法给Principal参数加了@RequestParam注解,这是错误的。Principal是Spring Security通过安全上下文自动注入的认证对象,并非URL请求参数。加了这个注解后,Spring会强制要求请求携带名为principal的查询参数,但你没传,直接触发400 Bad Request错误。
修复步骤
- 修改控制器方法参数,移除
@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); }
- 可选优化(简化代码):
如果你的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); }
- 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
相关产品推荐
相关产品推荐

