Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 957
isuru89 Avatar asked Jan 12 '19 03:01

isuru89


1 Answers

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")
like image 51
John Camerin Avatar answered Oct 07 '22 04:10

John Camerin