Protecting IDs on a URL in ASP.NET MVC
I'm working on a typical CRUD application in ASP.NET MVC where there will be multiple user accounts and each will have a number of items.
When a user is editing an item, they will be doing it on a URL such as /edit/5 where the number represents the ID of the row in the database.
I have some concerns about one user simply changing the ID to the ID of another user's item and being able to 开发者_StackOverflowchange it. To protect the ID, the following solutions have occurred to me:
- Encrypt it so it can't be easily changed - but then of course I have to have code to decrypt it each time it posts back.
- Change the database schema so that a GUID is also produced beside the ID and this is used in the URL.
Leave the readable ID as is and include the logged in user's UserID in queries for the item so that queries would look like:
database.Items.SingleOrDefault(c => c.UserID == [currently logged in user ID] && c.ID == itemID);
Maybe there's a better way or a way I have not thought of. What is your preferred method for protecting against this issue?
Definitely the third solution. Get the logged in user id from an encrypted cookie (cf. FormsAuthentication) and use it in the SQL query to verify that the item belongs to the user.
Never trust user input, always check if it do have access to it.
Store the UserID in the Session collection.
精彩评论