【发布时间】:2021-02-03 08:11:00
【问题描述】:
我试图只允许管理员或用户访问此方法,他们的 id 与其自己的相同。所以基本上 ID 为 1 的 John 将无法访问 ID 为 2 的 Matt 的订单。我一直在尝试使用 principal.id 来实现这一点,但它表示无法解析主体附近的 id id。有什么方法可以实现我想要的吗?谢谢。
@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);
}
【问题讨论】:
-
我认为这个答案可能对您有所帮助:stackoverflow.com/a/51713982/14056755
-
谢谢。该帖子内容丰富,但我的代码确实有效,但在
principal.id附近显示Cannot resolve property or method 'id' (dynamic property?)。不知道为什么以及如何解决这个问题。
标签: java spring-boot