【问题标题】:How Do I Implement PostFilter to PagingAndSortingRepository?如何实现 PostFilter 到 PagingAndSortingRepository?
【发布时间】:2016-09-25 23:52:57
【问题描述】:

我正在寻找如何为PagingAndSortingRepository 接口实现@PostFilter 注释

我创建了我的自定义存储库类扩展

public interface PublishableEntityRepository<T, ID extends Serializable>
        extends PagingAndSortingRepository<T, ID> {
    @PostFilter("hasPermission(filterObject, 'read')")
    Page<T> findAll(Pageable var1);
}

然后创建了一个自定义的PermissionEvaluator

public class AccessPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        boolean hasPermission = false;

        if (authentication != null) {
            User user = (User) authentication.getPrincipal();
            if (((PublishableEntity) o).getStatus().equals(AccessStatus.PUBLISHED)) {
                hasPermission = true;
            }
        }

        return hasPermission;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}

但是,IllegalArgumentException 被抛出:

RepositoryRestExceptionHandler - 过滤器目标必须是集合或数组类型,但第 0 页(共 0 页)包含 UNKNOWN 实例

我知道有问题的 filterObject 是一个 Page 类,那么如何过滤页面内容?

【问题讨论】:

    标签: java spring-security spring-data-rest


    【解决方案1】:

    找到答案,它是使用@Query 和带有安全扩展的SpEL。

    @NoRepositoryBean
    public interface PublishableEntityRepository<T, ID extends Serializable>
           extends PagingAndSortingRepository<T, ID> {
        @PostFilter("hasPermission(filterObject, 'read')")
        List<T> findAll();
    
        @PostAuthorize("hasPermission(returnObject, 'read')")
        T findOne(ID id);
    
        // where entity.status is PUBLISHED or security SpEL with hasRole
        @Query("select o from #{#entityName} o where o.status = 'PUBLISHED' " +
            "or 1 = ?#{security.hasRole('ROLE_ADMIN') ? 1 : 0}")
        Page<T> findAll(Pageable var1);
    }
    

    http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#data-query

    【讨论】:

    • 我们可以将 hasPermission 与 Page 一起使用,例如@Query("select o from #{#entityName} o where 1 = ?#{security.hasPermission(filterObject, 'read') ? 1 : 0}") Page&lt;T&gt; findAll(Pageable var1);
    • security.hasPermission(filterObject, 'read') 将不起作用,因为 filterObject 返回页面实例。经过大量调试才发现...似乎hasPermission,即使使用Spring扩展,也无法使用分页
    猜你喜欢
    • 2023-03-23
    • 2023-04-08
    • 2023-03-16
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多