How @PostFilter and @PreFilter work

梦想与她 提交于 2020-01-01 02:36:53

问题


Being new to spring annotations, I need a clarification for the below code.

@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.


回答1:


@PreFilter and @PostFilter are designated to use with Spring security to be able to filter collections or arrays based on the authorization.

To have this working, you need to use expression-based access control in spring security (as you have in your example)

@PreFilter - filters the collection or arrays before executing method.

@PostFilter - filters the returned collection or arrays after executing the method.

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)

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

@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.



来源:https://stackoverflow.com/questions/28647921/how-postfilter-and-prefilter-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!