Reputation: 45
Assume we have endpoint like this /users/{userId}/messages/{messageId}
and which is exposed via @DeleteMapping
(as endpoint suggest's, it delete's message with specified ID, for specified user).
Message
can be deleted in two cases: you are moderator, or you are owner of the message. The first part is quiet easy, you can add in Security configuration
that you need ROLE_MODERATOR
to use this endoint. But there is second case, when you can delete message if you are owner. How to implement it properly? If you add ROLE_MODERATOR
in Security configuration
you are disabling enpoint for non moderator users (including some owners of message).
Assume we have service called AuthenticatedUserHolder
with method getLoggedUserID()
which will return userID
(session, JWT or sth). Is there any way to combine ROLE_MODERATOR
or message owner?
Second question: Assume we have endpoint /users/{id}/addresses
with @PutMapping
and you can change address only if loggedUserID == id
. How to extract logic from service/facade
that will return 401/403
if loggedUserID != id
?
Edit: Method code:
SecurityContext authentication = SecurityContextHolder.getContext();
UserPrincipal loggedUser = (UserPrincipal) authentication.getAuthentication().getPrincipal();
return loggedUser.getUser().getPersonId();
UserPrincipal has extra field personId
.
Upvotes: 0
Views: 76
Reputation: 751
You can use @PreAuthorize annotation with a custom method Examples
Controller
@PreAuthorize("@beanName.beanMethodName(#controllerParamName)")
@GetMapping("/{controllerParamName}")
fun getMethod(@PathVariable("controllerParamName") param: Long) {
//whenever
}
Validation Bean
@Service
class BeanName {
fun beanMethodName(param: Long): Boolean {
return false
}
}
Upvotes: 1