Spring-Boot @PreAuthorize 仅允许管理员操作,或者如果经过身份验证的用户 ID 与路径参数 ID 相同 [英] Spring-Boot @PreAuthorize allow operation only for admin or if the authenticated user id is same as path parameter id

查看:24
本文介绍了Spring-Boot @PreAuthorize 仅允许管理员操作,或者如果经过身份验证的用户 ID 与路径参数 ID 相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有用户 CRUD 操作的控制器.

I have a controller which has User CRUD operations.

@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

}

此操作只允许管理员或用户本人使用.任何用户都不能编辑任何其他人的用户个人资料.

This operation is allowed only for the admin or user him/herself. No user can edit any other's user profiles.

我已经尝试过@PreAuthorize("hasRole('ROLE_ADMIN')),它只适用于管理员用户,但我想检查经过身份验证的用户是否与参数<指示的用户相同code>userId (authUser.getId() == userId).如何在注解中定义这个表达式?这是否可以不编写辅助函数.

I have tried @PreAuthorize("hasRole('ROLE_ADMIN')), it works only for admin user, but I want to check whether authenticated user is the same user as indicated by the parameter userId (authUser.getId() == userId). How can I define this expression inside the annotation? Is this possible without writing a helper function.

如果需要,我还使用 @CurrentUser 注释将当前经过身份验证的用户注入到控制器方法中.

I also have the current authenticated user injected in to the controller method using @CurrentUser annotation, in case it needs.

推荐答案

Spring 文档在这里应该会有所帮助.https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

The Spring docs should be helpful here. https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

您可以访问表达式中的主体或身份验证对象以及方法参数.因此,您在这里有多种选择,其中之一类似于以下内容:

You can access the principal or the authentication object in the expression as well as method arguments. So you have several options here, one of which would be something like the following:

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

这篇关于Spring-Boot @PreAuthorize 仅允许管理员操作,或者如果经过身份验证的用户 ID 与路径参数 ID 相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆