如何防止我的MongoRepository导出某些HTTP方法?

30

我正在使用spring-data-rest,我有一个像这样的MongoRepository:

@RepositoryRestResource
interface MyEntityRepository extends MongoRepository<MyEntity, String> {
}

我想允许GET方法,但禁用PUT、POST、PATCH和DELETE(只读Web服务)。

根据http://docs.spring.io/spring-data/rest/docs/2.2.2.RELEASE/reference/html/#repository-resources.collection-resource的说明,我应该像这样做:

@RepositoryRestResource
interface MyEntityRepository extends MongoRepository<MyEntity, String> {

    @Override
    @RestResource(exported = false)
    public MyEntity save(MyEntity s);

    @Override
    @RestResource(exported = false)
    public void delete(String id);

    @Override
    @RestResource(exported = false)
    public void delete(MyEntity t);
}

看起来不起作用,因为我仍然可以进行PUT、POST、PATCH和DELETE请求。


1
那应该可以工作,你能提供一个测试用例/测试项目来展示这个失败吗? - Oliver Drotbohm
今天再次测试后,它实际上可以工作。但是,我找不到如何限制 /myEntities 上的 GET 方法。将注释添加到 List<MyEntity> findAll(); 中没有任何效果。 - avandecreme
3
MongoRepository 继承了 PagingAndSortingRepository,因此您需要重新声明并注释 findAll(Pageable pageable) - Oliver Drotbohm
谢谢,我已经根据您的评论给出了答案。 - avandecreme
3个回答

41

感谢 Oliver,以下是覆盖方法:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends MongoRepository<Person, String> {

    // Prevents GET /people/:id
    @Override
    @RestResource(exported = false)
    public Person findOne(String id);

    // Prevents GET /people
    @Override
    @RestResource(exported = false)
    public Page<Person> findAll(Pageable pageable);

    // Prevents POST /people and PATCH /people/:id
    @Override
    @RestResource(exported = false)
    public Person save(Person s);

    // Prevents DELETE /people/:id
    @Override
    @RestResource(exported = false)
    public void delete(Person t);

}

我能禁用PUT吗?我希望所有新实体都通过POST创建。 - Laures
你可以尝试注释public Person insert(Person entity),但我怀疑它不会起作用。 - avandecreme

16

虽然回复有些晚了,但是如果你需要阻止实体的全局HTTP方法,可以尝试这个方法。

@Configuration
public class DataRestConfig implements RepositoryRestConfigurer {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
         config.getExposureConfiguration()
                .forDomainType(Person.class)
                .withItemExposure(((metdata, httpMethods) -> httpMethods.disable(HttpMethod.PUT, HttpMethod.POST, ... )))
                .withCollectionExposure((metdata, httpMethods) -> httpMethods.disable(HttpMethod.PUT, HttpMethod.POST, ...));
    }
}

3

为什么不直接像这样使用?

@Configuration
public class SpringDataRestConfiguration implements RepositoryRestConfigurer {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration restConfig) {
        restConfig.disableDefaultExposure();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接