如何在SpEL中获取PreAuthorize中的通用存储库的entityName或接口名称

时间:2016-08-26 18:23:08

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

我想创建一个通用的安全crud存储库,并使用preauthorize注释每个方法,但是我无法获取如何检索实体类名称

@NoRepositoryBean
public interface AbstractEntityRepository<T extends AbstractEntity> extends CrudRepository<T, String> {
    @Override
    @PreAuthorize("hasPermission(null, #entityName, 'find');
    Iterable<T> findAll();
}

public interface UserRepository extends AbstractEntityRepository<User> {}

在这种情况下,entityName始终为null。

@Component
@Log
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission)
        log.fine("type " + targetType); // <- null
        return true;
    }
...

知道如何获得“User”或“UserRepository”吗?

1 个答案:

答案 0 :(得分:0)

@Component
public class ClassTypeResolver {
    public static String resolve(Object object) {
        if (AopUtils.isJdkDynamicProxy(object)) {
            try {
                return ((SimpleJpaRepository) ((Advised)object).getTargetSource().getTarget()).getDomainClass().getCanonicalName();
            } catch (Exception e) {
                return null;
            }
        } else {
            return ((SimpleJpaRepository) object).getDomainClass().getCanonicalName();
        }
    }
}