我正在使用spring boot,并且我在WebSecurityConfigurerAdapter中启用了全局方法安全性
@EnableGlobalMethodSecurity(prePostEnabled = true, order = Ordered.HIGHEST_PRECEDENCE)
下面是我的 Controller 代码
@PreAuthorize("hasAnyRole('admin') or principal.id == id")
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public User updateUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto)
{ ....}
但是,当非管理员用户尝试执行 PUT 请求时,JSR303 验证器将在 @PreAuthorize 之前启动。
例如,非管理员用户最终会得到类似“需要名字”而不是“拒绝访问”的内容。但是在用户提供名字变量以通过验证器后,拒绝访问被返回。
有谁知道如何在@Valid 或@Validated 之前强制检查@PreAuthorize?
而且我必须使用这种方法级别的授权而不是基于 url 的授权来执行一些复杂的规则检查。
最佳答案
我有同样的问题,我找到了这篇文章。 M. Deinum 的评论帮助我理解出了什么问题
这是我所做的:
例子 :
@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("hasRole('MY_ROLE')")
public ResponseEntity createNewMessage(@RequestBody CreateMessageDTO createMessageDTO) {
// The user is authorized
return createNewMessageWithValidation(createMessageDTO);
}
private ResponseEntity createNewMessageWithValidation(@Valid CreateMessageDTO createMessageDTO) {
// The DTO is valid
return ...
}
关于spring-mvc - 如何使@PreAuthorize 具有比@Valid 或@Validated 更高的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923360/