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

Viewed 5461

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 Answers
Related