Spring Boot@PreAuthorize只允许admin操作,或者如果经过身份验证的用户id与路径参数id相同



我有一个控制器,它有User 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

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

@PreAuthorize("hasRole('ROLE_ADMIN) or #authUser.id == #userId")

最新更新