我有一个具有用户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用户,但是我想检查通过身份验证的用户是否与参数userId(authUser.getId() == userId)所示的用户相同。如何在注释中定义此表达式?不用编写辅助函数就能做到这一点。
如果需要的话,我还会使用@CurrentUser注释将当前经过身份验证的用户注入到控制器方法中。