Spring-Boot @PreAuthorize 仅允许管理员操作或经过身份验证的用户 id 与路径参数 id 相同时

2024-01-07

我有一个具有用户 CRUD 操作的控制器。

@Controller
public class UserController {

  // @TODO need to check whether userId == authUser.id or authUser is admin??
  //
  @PreAuthorize("hasRole('ROLE_ADMIN) or ...???...")
  @PostMapping("/user/{id}/edit")
  public boolean editUser(@PathVariable("id") long userId,
                          @RequestBody User newUserObj,
                          @CurrentUser authUser) {
     // I don't like to always call a helper function from here
     // check(authUser.getId() == userId);

     return userService.edit(userId, newUserObj);
  }

 // ... rest of the methods

}

此操作仅允许管理员或用户本人进行。任何用户都不能编辑其他人的用户配置文件。

我努力了@PreAuthorize("hasRole('ROLE_ADMIN')),它仅适用于管理员用户,但我想检查经过身份验证的用户是否与参数指示的用户相同userId (authUser.getId() == userId)。如何在注释中定义这个表达式?如果不编写辅助函数,这可能吗?

我还将当前经过身份验证的用户注入到控制器方法中,使用@CurrentUser注释,以备不时之需。


Spring 文档在这里应该有帮助。https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

您可以访问表达式中的主体或身份验证对象以及方法参数。因此,您在这里有多种选择,其中之一如下所示:

@PreAuthorize("hasRole('ROLE_ADMIN) or #authUser.id == #userId")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring-Boot @PreAuthorize 仅允许管理员操作或经过身份验证的用户 id 与路径参数 id 相同时 的相关文章

随机推荐