【问题标题】:How to allow the REST call in Spring only for the user modifying itself?如何只允许用户修改自己在 Spring 中调用 REST?
【发布时间】:2019-10-20 23:17:20
【问题描述】:

我有

@PutMapping("/users/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public User updateUser(@PathVariable("id") Long userId, @RequestBody User updatedUser){
...
}

我知道我可以使用 @PreAuthorize 来保护方法,具体取决于您的角色。但我只想让这个 API 调用只允许用户自己编辑。如何做到这一点?

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-security


    【解决方案1】:

    @PreAuthorize 中,您可以使用SpEL 来访问输入参数的属性。它还提供了一个内置的表达式authentication 来访问Authentication 实例(以及一个快捷方式principal 来访问Authentication.getPrincipal())从当前SecurityContext

    对于默认的 JDBC 身份验证,主体是不存储用户 ID 的 UserDetails 实例。因此,我建议您对其进行自定义以包含用户 ID。之后,您可以执行以下操作:

    @PutMapping("/users/{id}")
    @ResponseStatus(HttpStatus.ACCEPTED)
    @PreAuthorize("#updatedUser.userId == principal.userId")
    public User updateUser(@PathVariable("id") Long userId, @RequestBody User updatedUser){
    
    }
    

    【讨论】:

    • 这是答案,谢谢。我不知道为什么我的问题总是被否决?
    • 我也不确定。似乎有人对你的问题投了反对票,我不知道他为什么投反对票....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多