Spring-Boot @PreAuthorize allow operation only for admin or if the authenticated user id is same as path parameter id

六眼飞鱼酱① 提交于 2020-08-27 22:09:51

问题


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.

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.

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


回答1:


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")


来源:https://stackoverflow.com/questions/54156564/spring-boot-preauthorize-allow-operation-only-for-admin-or-if-the-authenticated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!