我正在使用spring-data-rest
并通过存储库公开端点以对我的实体进行CRUD
其中一个实体应该可以使用PATCH / PUT方法进行更新,但是不可能使用POST方法创建新实例。
似乎这两个操作都通过save
方法,因此似乎无法仅导出部分请求:
@RestResource(exported = ?)
@Override
<S extends User> S save(S s);
实现这一目标的最佳方法是什么?
我应该覆盖save
方法吗?写自定义Validator
?
答案 0 :(得分:2)
您可以使用
Validators并在errors
参数中添加错误
Event Handlers,抛出异常并通过@ControllerAdvice
捕获,返回自定义消息或HTTP状态代码
Custom Controllers并手动处理请求。请参阅此答案:https://stackoverflow.com/a/41351429/7226417
前两个应该听BeforeCreateEvent
。
答案 1 :(得分:0)
一种解决方案是扩展WebSecurityConfigurerAdapter(在spring-security-config中可用)以拒绝对目标URL的POST请求的访问:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/path_to_target_url").denyAll();
}
}
任何POST到目标网址的尝试都将失败,并显示401 Unauthorized
错误。