如何将PostFilter实现到PagingAndSortingRepository?

时间:2016-05-27 15:11:22

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

我正在寻找如何为@PostFilter界面实施PagingAndSortingRepository注释

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

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 - 过滤目标必须是集合或数组类型,但是包含UNKNOWN实例的第0页0

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

1 个答案:

答案 0 :(得分:2)

找到答案,它是使用@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