我有一个具有用户 CRUD 操作的 Controller 。
@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
将当前经过身份验证的用户注入(inject)到 Controller 方法中注释,以备不时之需。
最佳答案
Spring 文档在这里应该会有帮助。 https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html
您可以访问表达式中的主体或身份验证对象以及方法参数。因此,您在这里有多种选择,其中之一类似于以下内容:
@PreAuthorize("hasRole('ROLE_ADMIN) or #authUser.id == #userId")
关于java - Spring-Boot @PreAuthorize 只允许对管理员进行操作,或者如果经过身份验证的用户 ID 与路径参数 ID 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156564/