gpt4 book ai didi

spring-boot - 存储库查询的 Spring Security 授权

转载 作者:行者123 更新时间:2023-12-02 03:06:19 25 4
gpt4 key购买 nike

如果我有一个订单列表存储在表中并通过 url/orders/{id} 公开,我想通过更改路径 id 来限制委托(delegate)人访问订单url,Spring Security 如何帮助我查询 Spring Data JPA 存储库。

基于 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 方法名称功能并避免在这种情况下重写查询。

最佳答案

我认为您正在寻找的是来自 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);

您可以将 springs 表达式语言与 @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 角色。如果用户拥有该特权,则将返回未更改的列表,否则它将进行过滤并仅返回那些“来自”与当前经过身份验证的用户相关联的订单。

关于spring-boot - 存储库查询的 Spring Security 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42569029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com