Reputation: 52
I would like to secure my rest api , i am already using JWT to authenticate users . but what if a user that have a JWT change the payload of a PUT request . for example i have a put request to update a post. and i need to pass post ID in the Body , how can i prevent users from changing the post id and sending it again in postman ? if he have a jwt he can execute the put api and change any post he wants . i thought about extracting the User Id from the JWT and check if the Post belongs to him or not . but i never seen some logic like that . does it exist like that ? to check if the object to update belongs to the JWT before updating it .
Upvotes: 0
Views: 856
Reputation: 616
I think first you need to verify the payload sent to the server, and then check if the user has permission to do a PUT request on that item or entity. In your case get the post, Check if it belongs to the user if it does make the changes if it does not return an unauthorized response (HTTP status code 401 Unauthorized) You can also implement it in a middleware before accessing the logic of your function to check if the user has the privileges to do so.
Upvotes: 0
Reputation: 377
Common practice is reading the resource before mutation. Then assert user's ID from decoded token with that resource's owner ID.
Upvotes: 0
Reputation: 33881
Your reasoning is sound: it would be naïve to think that authenticated users won't act maliciously. In the server-side code that handles your PUT
route, you should validate the payload and ensure that the authenticated user has the correct permissions/authority to perform the action in the payload before actually making the change on the user's behalf.
Upvotes: 1