我有一种情况,我需要将路径变量作为参数传递给预授权
@RequestMapping(value="/page/{cmd}", method = RequestMethod.GET)
@PreAuthorize("hasRole(#cmd)")
public void method(@PathVariable String cmd, HttpServletRequest request, HttpServletResponse response){
// my stuff
}
它不起作用。有人可以建议我如何在预授权中使用路径变量吗?
Spring Security 的
@PreAuthorize
用于授权对方法的访问。它对 Spring MVC 不太了解,特别是它的 @RequestMapping
注释。
像
#cmd
这样的名称将引用方法参数,而你的 cmd
参数为空。改为:
@PathVariable("cmd") String cmd
这样,
cmd
路径变量将绑定到cmd
方法参数,然后该方法参数将被#cmd
中的@PreAuthorize
绑定。
分享一个如何使用变量(路径)、身份验证对象(spring)的示例
@PatchMapping("/users/{id}/update-password")
@PreAuthorize("hasAuthority('USER_WRITE') OR (#id == authentication.details.get('userId'))")
@ResponseStatus(HttpStatus.OK)
public UserModel updatePassword(@PathVariable long id, @RequestBody PasswordForm passwordForm) {
// my code ....
}
端点说明:如果满足2个条件之一,端点允许更新密码: