Spring boot 存储库查询的Spring安全授权
如果我有一个存储在表中并通过url/orders/{id}公开的订单列表,并且我想通过更改url中的路径id来限制主体访问订单,那么Spring安全性如何帮助我查询Spring数据JPA存储库 基于Spring Security 4 youtube视频:-Spring boot 存储库查询的Spring安全授权,spring-boot,spring-security,authorization,spring-data,Spring Boot,Spring Security,Authorization,Spring Data,如果我有一个存储在表中并通过url/orders/{id}公开的订单列表,并且我想通过更改url中的路径id来限制主体访问订单,那么Spring安全性如何帮助我查询Spring数据JPA存储库 基于Spring Security 4 youtube视频:- interface OrderRepository extends Repository<Order, Long> { @Query("select o from Order o where o.id = ?1 and
interface OrderRepository extends Repository<Order, Long> {
@Query("select o from Order o where o.id = ?1 and o.from.id = ?{#principal.id} ")
Optional<Order> findOrder(long id);
}
这是最好的做法吗?理想情况下,我希望使用Spring数据方法名称功能,避免在这种情况下重写查询。我认为您需要的是Spring security的@PreAuthorize或@PostAuthorize。它们是spring中方法级安全性的注释。它们将允许您根据角色和其他属性进行限制
interface OrderRepository extends Repository<Order, Long> {
@PreAuthorize("hasRole('ROLE_ADMIN')") // Allows only users with admin privileges
@Query("select o from Order o where o.id = ?1 and o.from.id = ?{#principal.id} ")
Optional<Order> findOrder(long id);
}
编辑:
如果您希望仅在当前经过身份验证的用户与订单的发件人关联时返回订单
@PostAuthorize("returnObject.from == authentication.name")
Optional<Order> findOrder(long id);
您可以将springs表达式语言与@PreAuthorize@PostAuthorize注释一起使用
希望这有帮助
编辑2:您可以使用@PreFilter和@PostFilter来筛选集合
范例
@PostFilter("filterObject.from == authentication.name")
List<Order> findOrder(long id);
这将在列表中运行,并且仅返回来自当前已验证用户的订单。您还可以组合表达式
@PostFilter("hasRole('ROLE_ADMIN') or filterObject.from == authentication.name")
List<Order> findOrder(long id);
这将检查当前经过身份验证的用户是否具有role_ADMIN角色。如果用户拥有该权限,则将返回未更改的列表,否则它将过滤并仅返回与当前已验证用户关联的那些订单。如何@PreAuthorize do authorization以每个用户为基础,而不是以角色为基础?@aprofromedia编辑了我的帖子。PostAuthorize将与当前经过身份验证的用户一起检查returned Order对象的from成员变量。请冷却我们如何为findAll授权实现此逻辑。我不想使用@PostFilter并过滤整个列表。我更新了我的回复,但只是读到你不想使用PostFilter。没有PostFilter,我不确定有什么方法可以做到这一点