Spring安全授权存储库查询

问题描述:

如果我有一个存储在表中并通过url/orders/{id}公开的订单列表,并且我想通过更改url中的路径id来限制主体访问订单,Spring Security如何帮助我查询Spring Data JPA存储库。Spring安全授权存储库查询

基于Spring Security的4个YouTube视频: -

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 Data方法名称功能,并避免在这种情况下重写Query。

我想你要找的是Spring安全中的@PreAuthorize或@PostAuthorize。它们是春季方法级别安全性的注释。他们将允许您根据角色和其他属性进行限制。

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); 

}

https://spring.io/blog/2013/07/04/spring-security-java-config-preview-method-security/


编辑:

如果你看如果当前认证的用户与谁的顺序与关联只返回订单。

@PostAuthorize("returnObject.from == authentication.name") 
Optional<Order> findOrder(long id); 

您可以使用弹簧表达式语言和@PreAuthorize @PostAuthorize批注。

http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html

希望这有助于


编辑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。如果用户具有该特权,未改变的列表将会返回,否则它将过滤并且仅返回那些“from”与当前经过验证的用户相关联的订单。

+0

@PreAuthorize如何在每个用户的基础上进行授权,而不是根据角色进行授权? – aprofromindia

+0

@aprofromindia编辑了我的帖子。 PostAuthorize将使用当前经过身份验证的用户检查返回的Order对象的from成员变量。 – jmw5598

+0

酷我们怎样才能实现findAll()授权这个逻辑请。我不想使用@PostFilter()并过滤整个列表。 – aprofromindia