如何在@Preauthorize中使用路径变量

问题描述 投票:0回答:2

我有一种情况,我需要将路径变量作为参数传递给预授权

    @RequestMapping(value="/page/{cmd}", method = RequestMethod.GET)
    @PreAuthorize("hasRole(#cmd)") 
     public void method(@PathVariable String cmd, HttpServletRequest request,  HttpServletResponse response){
// my stuff
}

它不起作用。有人可以建议我如何在预授权中使用路径变量吗?

jakarta-ee spring-security pre-authentication
2个回答
19
投票

Spring Security 的

@PreAuthorize
用于授权对方法的访问。它对 Spring MVC 不太了解,特别是它的
@RequestMapping
注释。

#cmd
这样的名称将引用方法参数,而你的
cmd
参数为空。改为:

@PathVariable("cmd") String cmd

这样,

cmd
路径变量将绑定到
cmd
方法参数,然后该方法参数将被
#cmd
中的
@PreAuthorize
绑定。


0
投票

分享一个如何使用变量(路径)、身份验证对象(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个条件之一,端点允许更新密码:

  • 如果您有 USER_WRITE 权限
  • 或者如果userId(您在spring security中自定义的)与id参数(路径变量)匹配

参考:sprign security - 表达式基础访问控制

© www.soinside.com 2019 - 2024. All rights reserved.