我认为您正在寻找的是来自 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);
}
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 注释的springs 表达式语言。
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”与当前经过身份验证的用户相关联的那些订单。