I am trying to allow access to this method only for admins or users, whose id is the same as its own. So basically John with ID 1 won't be able to access Matt's orders with ID 2. I've been trying to achieve this with principal.id, but it says that id id near principal cannot be resolved. Is there any way to achieve what I want? Thank you.
@GetMapping("/users/{userId}/orders")
@PreAuthorize("hasRole('ADMIN') or #userId == principal.id")
List<Order> getOrdersByUserId(@PathVariable Long userId) {
log.info("Request to get user's orders by userId: {}", userId);
if (!userRepository.existsById(userId)) {
throw new UserNotFoundException(userId);
}
return orderRepository.findByClientId(userId);
}