java @PostFilter 和 @PreFilter 如何工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28647921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How @PostFilter and @PreFilter work
提问by Zack
Being new to spring annotations, I need a clarification for the below code.
作为 spring 注释的新手,我需要对以下代码进行说明。
@PostFilter("hasPermission(filterObject, 'READ') or hasRole('ROLE_ADMIN')")
public List<User> getUsers(String orderByInsertionDate,
Integer numberDaysToLookBack) throws AppException
;
;
So this means that the list of users returned by getUsers will only contain those elements which have full "READ"
access to the calling object or the calling object has role as "ROLE_ADMIN"
. Thanks.
因此,这意味着 getUsers 返回的用户列表将仅包含"READ"
对调用对象具有完全访问权限或调用对象具有角色为 的那些元素"ROLE_ADMIN"
。谢谢。
回答by vtor
@PreFilter
and @PostFilter
are designated to use with Spring security to be able to filter collections or arrays based on the authorization.
@PreFilter
并被@PostFilter
指定与 Spring security 一起使用,以便能够根据授权过滤集合或数组。
To have this working, you need to use expression-based access control in spring security (as you have in your example)
要使其正常工作,您需要在 spring 安全性中使用基于表达式的访问控制(如您的示例中所示)
@PreFilter- filters the collection or arrays before executing method.
@PreFilter- 在执行方法之前过滤集合或数组。
@PostFilter- filters the returned collection or arrays after executing the method.
@PostFilter- 在执行方法后过滤返回的集合或数组。
So, let's say your getUser()
returns List of Users. Spring Security will iterate through the list and remove any elements for which the applied expression is false (e.g. is not admin, and does not have read permission)
因此,假设您getUser()
返回用户列表。Spring Security 将遍历列表并删除任何应用表达式为 false 的元素(例如,不是管理员,并且没有读取权限)
filterObject is built-in object on which filter operation is performed and you can apply various conditions to this object (basically all built-in expressions are available here, e.g. principal
, authentication
), for example you can do
filterObject 是执行过滤操作的内置对象,您可以对这个对象应用各种条件(基本上所有内置表达式都在这里可用,例如principal
,authentication
),例如您可以这样做
@PostFilter ("filterObject.owner == authentication.name")
Though those filters are useful, it is really inefficient with large data sets, and basically you lose control over your result, instead Spring controls the result.
尽管这些过滤器很有用,但对于大数据集来说确实效率低下,而且基本上你失去了对结果的控制,取而代之的是 Spring 控制结果。