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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With