Issue
When I log in to my API via postman, a JWT is generated. With this jwt I create data for a specific user. But when I am connected with this user and his JWT, when I make a GET request from POSTMAN with the connected user's JWT, I get a 400 error saying that the request is bad. I do not understand why. My Tomcat server port IS NOT 8080 but 7777... Just bellow my controller with GET method :
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/weights")
public class WeightRecordController {
@Autowired
AppUserRepository appUserRepository;
@Autowired
PersonRepository personRepository;
private final Logger logger = LoggerFactory.getLogger(WeightRecordController.class);
public Long getAppUserConnectedId(Principal principal) {
if (!(principal instanceof UsernamePasswordAuthenticationToken)) {
throw new RuntimeException(("User not found"));
}
logger.info("USER IS PRESENT IN DATABASE FROM FUNCTION 'getAppUserConnectedId()'");
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) principal;
AppUser appUserFinded = appUserRepository.findByAppUsername(token.getName());
return appUserFinded.getIdUser();
}
@GetMapping("/all")
public ResponseEntity<List<WeightRecord>> getAllWeights(@RequestParam 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);
}
}
Solution
In fact JWT token is transfered by request's header, so i have simply delete the @RequestParam from my endpoint and it work ! Just bellow my new code for the endpoint concerned :
@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);
}
Answered By - Quentin Genet
Answer Checked By - Mildred Charles (JavaFixing Admin)