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

isuru89 :

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.

John Camerin :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91551&siteId=1