Java APIRest - Postman错误400使用GET方法和JWT的错误请求

yvgpqqbh  于 2022-11-07  发布在  Postman
关注(0)|答案(2)|浏览(256)

当我通过postman登录到我的API时,会生成一个JWT,使用这个JWT为特定用户创建数据,但是当我与这个用户及其JWT连接时,当我使用连接用户的JWT从Postman发出GET请求时,我得到一个400错误,说请求是坏的。我不明白为什么。我的Tomcat服务器端口不是8080而是7777...只是用GET方法在我的控制器下面:

  1. @CrossOrigin(origins = "*")
  2. @RestController
  3. @RequestMapping("/weights")
  4. public class WeightRecordController {
  5. @Autowired
  6. AppUserRepository appUserRepository;
  7. @Autowired
  8. PersonRepository personRepository;
  9. private final Logger logger = LoggerFactory.getLogger(WeightRecordController.class);
  10. public Long getAppUserConnectedId(Principal principal) {
  11. if (!(principal instanceof UsernamePasswordAuthenticationToken)) {
  12. throw new RuntimeException(("User not found"));
  13. }
  14. logger.info("USER IS PRESENT IN DATABASE FROM FUNCTION 'getAppUserConnectedId()'");
  15. UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) principal;
  16. AppUser appUserFinded = appUserRepository.findByAppUsername(token.getName());
  17. return appUserFinded.getIdUser();
  18. }
  19. @GetMapping("/all")
  20. public ResponseEntity<List<WeightRecord>> getAllWeights(@RequestParam Principal principal) {
  21. logger.info("GET /weights/all");
  22. Long appUserConnectedId = this.getAppUserConnectedId(principal);
  23. Person personToShow = personRepository.findById(appUserConnectedId).orElseThrow();
  24. return new ResponseEntity<List<WeightRecord>>(personToShow.getWeightsList(), HttpStatus.OK);
  25. }
  26. }
oknrviil

oknrviil1#

我不知道为什么Tomcat在端口8080上运行,而您在端口7777上调用API,但它返回代码400。这意味着您通过了应用程序的身份验证。您的get request @RequestParam主体,但它不显示在您的请求中

gj3fmq9x

gj3fmq9x2#

事实上JWT令牌是通过请求的头来传输的,所以我只需要从我的端点中删除@RequestParam,它就可以工作了!下面是我的新代码:

  1. @GetMapping("/all")
  2. public ResponseEntity<List<WeightRecord>> getAllWeights(Principal principal) {
  3. logger.info("GET /weights/all");
  4. Long appUserConnectedId = this.getAppUserConnectedId(principal);
  5. Person personToShow = personRepository.findById(appUserConnectedId).orElseThrow();
  6. return new ResponseEntity<List<WeightRecord>>(personToShow.getWeightsList(), HttpStatus.OK);
  7. }

相关问题