如何在我的控制器中进行验证(@Valid)之前检查安全性访问(@Secured或@PreAuthorize)? [英] How to check security acess (@Secured or @PreAuthorize) before validation (@Valid) in my 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);
}
我的需要是,当没有适当角色的客户端尝试创建用户时,即使发送的数据无效,控制器也会响应未授权".相反,如果客户端(没有适当的角色)尝试创建具有错误数据的用户,则我的控制器以@Valid消息(例如:密码不能为空")响应,而我希望它响应未授权" .
My need is when a client without the appropriate role tries to create a user, the controller responds "Not authorized" even if the data sent are not valid. Instead of that, if the client (without the appropriate role) tries to create a user with wrong data, my controller responds with the @Valid message (ex : "password cannot be empty"), while I want it responds "not authorized".
在PreAuthorized
界面中,我们可以找到以下句子:
In the PreAuthorized
Interface we can find this sentence :
用于指定方法访问控制表达式的注释,将对其进行评估以确定是否允许方法调用.
Annotation for specifying a method access-control expression which will be evaluated to decide whether a method invocation is allowed or not.
但事实并非如此.
推荐答案
您不能直接执行此操作,因为@Valid
是在之前进行了实际的方法调用,因此在之前进行了处理 @PreAuthorize
.
You can not do this directly, since @Valid
is processed before an actual method call and as a result before @PreAuthorize
.
但是,您可以做的是恰好在模型(userRO)之后注入BindingResult
,并且这样做-控制验证过程.然后检查BindingResult
是否有一些错误,如果有,则返回错误的请求响应(类似于spring的操作).
But what you can do instead is to inject BindingResult
just right after your model (userRO) and in doing so - take control of validation process. Then check if BindingResult
has some errors and if so return bad request response (similar to what spring does).
示例:
@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));
}
这篇关于如何在我的控制器中进行验证(@Valid)之前检查安全性访问(@Secured或@PreAuthorize)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!