这是我的 Controller 代码:
@PreAuthorize("hasRole('CREATE_USER')")
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public UserReturnRO createUser(@Valid @RequestBody UserRO userRO) throws BadParameterException{
return userService.createUser(userRO);
}
我的需要是当没有适当角色的客户端尝试创建用户时,即使发送的数据无效, Controller 也会响应“未授权”。取而代之的是,如果客户端(没有适当的角色)尝试使用错误数据创建用户,我的 Controller 会以 @Valid 消息响应(例如:“密码不能为空”),而我希望它响应“未授权” .
在PreAuthorized
界面我们可以找到这句话:
Annotation for specifying a method access-control expression which will be evaluated to decide whether a method invocation is allowed or not.
但好像不是这样的。
最佳答案
你不能直接这样做,因为 @Valid
在实际方法调用之前处理,结果之前 @PreAuthorize
.
但是你可以做的是注入(inject) BindingResult
就在您的模型(userRO)之后并这样做 - 控制验证过程。然后检查是否 BindingResult
有一些错误,如果是,则返回错误的请求响应(类似于 spring 所做的)。
例子:
@ResponseBody
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasRole('CREATE_USER')")
public ResponseEntity<?> createUser(@RequestBody @Valid UserRO userRO, BindingResult result) {
if (result.hasErrors()) {
return ResponseEntity.badRequest().body(result.getAllErrors());
}
return ResponseEntity.ok(userService.createUser(userRO));
}
关于spring - 如何在我的 Controller 中验证(@Valid)之前检查安全访问(@Secured 或 @PreAuthorize)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22780668/