小编isu*_*u89的帖子

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

我有一个具有用户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

}
Run Code Online (Sandbox Code Playgroud)

此操作仅允许管理员或用户使用。没有用户可以编辑任何其他人的用户配置文件。

我已经尝试过@PreAuthorize("hasRole('ROLE_ADMIN')),它仅适用于admin用户,但是我想检查通过身份验证的用户是否与参数userIdauthUser.getId() == userId)所示的用户相同。如何在注释中定义此表达式?不用编写辅助函数就能做到这一点。

如果需要的话,我还会使用@CurrentUser注释将当前经过身份验证的用户注入到控制器方法中。

java spring-security spring-el spring-boot

3
推荐指数
1
解决办法
838
查看次数

标签 统计

java ×1

spring-boot ×1

spring-el ×1

spring-security ×1