0

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);
}
Captain Jacky
  • 888
  • 1
  • 12
  • 26
  • 1
    I think this answer might help you: https://stackoverflow.com/a/51713982/14056755 – Marcin Rzepecki Oct 20 '20 at 13:48
  • Thanks. The post was informative, but nonetheless my code did work actually, but near `principal.id` it says `Cannot resolve property or method 'id' (dynamic property?)`. Not sure why and how to fix that. – Captain Jacky Oct 21 '20 at 07:32

1 Answers1

0

Use authentication.principal.id instead of principal.id, the warning will go away.