spring - 如何在我的 Controller 中验证(@Valid)之前检查安全访问(@Secured 或 @PreAuthorize)?

标签 spring validation spring-mvc spring-security controller

这是我的 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/

相关文章:

java - Spring Boot - 在 Controller 方法之间保存用户

HTML5 &lt;input&gt; 必需属性但不在 <form> 内

c# - 在 C# 中验证文本框输入

java - 尝试使用 Spring Boot REST 从 POST 读取 JSON 字符串

java - glassfish 服务器如何在没有 servlet 映射的情况下提供静态资源

spring - zk-grails与Spring安全性集成

java - 为什么我会看到 Springboot starter 2.1.2 pom 不可解析问题?

regex - Spring @RequestMapping 用于除/api/或/rest/之外的所有内容(否定正则表达式中的特定单词)

java - @QuerydslPredicate 抛出异常

JavaFX WebView : how to check if form is valid?