Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent users from modifying cookie values

I am storing an ItemId value in a cookie to keep track of the users currently selected item. This ItemId is not sensitive data, I don't care if users can see the value. This value will need to be accessed on most pages, that was why the decision was made to keep the value in a cookie instead of the database. If it were in the db i wouldn't have this problem.

The problem is the user could modify that cookie ItemId to another users ItemId and they would then potentially be able to perform actions on someone else's item. That is unless I verify the cookie value against the database to make sure it is valid for the user logged in. Which means a hit to the db defeating the purpose of putting the value in a cookie.

Basically my question is how do I prevent the user from modifying the cookie or at least knowing it was modified? I know the .NET forms authentication cookie stores user id and role data, so they obviously have the same issue..

My initial thought was to encrypt the values in the cookie. I understand the cookie could still be hijacked, but would this at least prevent tampering its values?

Maybe I should have gone the db route instead?

Thanks.

like image 353
Ryan Sampson Avatar asked Sep 18 '25 06:09

Ryan Sampson


1 Answers

The standard answer this "No data from the browser is trustworthy".

None.

verify the cookie value against the database to make sure it is valid for the user logged in.

Correct. That's the solution.

Which means a hit to the db defeating the purpose of putting the value in a cookie.

True on the DB hit, but irrelevant, since databases have cache.

The cookie, however, still has some value.

What you should do, however, is use a framework that maintains sessions and use the session to track this. Not a cookie you invented yourself.

like image 88
S.Lott Avatar answered Sep 21 '25 21:09

S.Lott