我有一个具有用户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'))
,它仅适用于admin用户,但是我想检查已认证用户是否与参数userId
(authUser.getId() == userId
)所指示的用户相同。如何在注释中定义此表达式?不用编写辅助函数就能做到这一点。
如果需要,我还使用@CurrentUser
批注将当前经过身份验证的用户注入到控制器方法中。
答案 0 :(得分:4)
Spring文档在这里应该会有所帮助。 https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html
您可以访问表达式中的主体或身份验证对象以及方法参数。因此,您在此处有几种选择,其中一种可能类似于以下内容:
@PreAuthorize("hasRole('ROLE_ADMIN) or #authUser.id == #userId")