REST - send user ID and get user ID from director

I would like to know the correct approach to defining a RESTful service for a common use case.

I am writing a RESTful API to update the current user profile. Should we send the current user id in the request? This will require server-side validation, so that the user can edit their own data. Therefore, I will need to add a verification of the user ID and the main object. In addition, the client side must somewhere support the current user ID.

POST /user/{id}

Alternatively, I can simply skip sending the user ID and get the user data from the Principal object. As we know, there is nothing like a secure stateless API, will this be the right approach?

I am not aware of any function in Spring that would confirm the current user for me, as required in the first approach. If he is present, please let me know.

+4
source share
1 answer

Consider the case when an administrator who is allowed to update other users wants to send the update. In this case, it will be POST /user/{id}. There is no reason to believe that this should not be for the average user.

Spring Security @PreAuthorize . :

@PostMapping("/user/{id}")
@PreAuthorize("hasRole('ADMIN') || (principal.id == #id)")
public User updateUser(@RequestBody User newInfo, @PathVariable Long id) {
    ...
}
+2

All Articles