我正在使用Spring Boot spring-data-rest创建CrudRepository,并向用户公开其余端点。在CrudRepository中限制创建动作,只允许编辑动作
但我想阻止用户创建新的记录。 只允许用户更新现有的记录。
如何实现? CrudRepository没有create
方法,只是save
delete
...
我正在使用Spring Boot spring-data-rest创建CrudRepository,并向用户公开其余端点。在CrudRepository中限制创建动作,只允许编辑动作
但我想阻止用户创建新的记录。 只允许用户更新现有的记录。
如何实现? CrudRepository没有create
方法,只是save
delete
...
CrudRepository提供CREATE
和EDIT
采用相同的方法save
。 但是spring-data-rest通过HTTP方法POST,PUT,PATCH公开了这两个操作。
POST用于CREATE
,因此我们可以通过弹簧安全限制这种方法:antMatchers(HttpMethod.POST, “/ ...”)denyAll()
创建示例项目here。
您可以添加拦截器:
public class SecurityInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
// insert logic here to check if it's an update
return super.onSave(entity, id, state, propertyNames, types);
}
}
添加拦截器与application.yaml:
jpa:
properties:
hibernate:
ejb:
interceptor: hello.SecurityInterceptor
我发现使用'antMatchers(HttpMethod.POST,“/ ...”).denyAll()'来限制HTTP POST的方法。但谢谢你的答案。 – Akivamu
从您的评论下面看你没有问你的实际问题。您是否可以更新您的问题以符合您的实际问题,并将解决方案作为答案发布,以便可以帮助其他人解决类似问题? –