如何使@PreAuthorize的优先级高于@Valid或@Validated

我正在使用Spring Boot,并且已通过以下方式在WebSecurityConfigurerAdapter中启用了全局方法安全性:

@EnableGlobalMethodSecurity(prePostEnabled = true, order = Ordered.HIGHEST_PRECEDENCE)

下面是我的控制器代码

@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之前启动。例如,非管理员用户最终得到诸如“需要名字”之类的东西,而不是“拒绝访问”之类的东西。但是在用户提供了要通过验证程序的名字变量之后,拒绝访问被返回。

有谁知道如何强制@PreAuthorize在@Valid或@Validated之前得到检查?

而且我必须使用这种方法级别的授权而不是基于url的授权才能执行一些复杂的规则检查。

回答:

对于同一场景,我​​发现了通过弹簧过滤器实现安全性的建议。

另外,也许是另一种方法-尝试通过在@InitBinder中注册自定义验证器来使用验证(因此跳过@valid批注)。

要访问过滤器类中的主体对象:

  SecurityContextImpl sci = (SecurityContextImpl)     

session().getAttribute("SPRING_SECURITY_CONTEXT");

if (sci != null) {

UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();

}

在这种情况下,/ {id}是URL中的路径参数。要访问过滤器或拦截器类中的路径参数:

String[] requestMappingParams =    ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()

for (String value : requestMappingParams) {.

以上是 如何使@PreAuthorize的优先级高于@Valid或@Validated 的全部内容, 来源链接: utcz.com/qa/426334.html

回到顶部