Authentication cookie
I am writing a database authentication system for my web application, which is written in ASP.NET MVC. When someone allows, they must save their username in a cookie. Is it safe to just use HttpResponse.Cookies` to persist the cookie so that its value is the username? Wouldn't that be faked?
Storing only the username ... Is it correct and secure? Or should I keep the entire User object (if really possible)?
Thanks and sorry for my english.
source to share
No, storing a username is very insecure because it can be easily spoofed. Here are my recommendations:
- Use a token .
- Hash token when stored in the database.
- Make cookie HttpOnly .
Tokens can be generated by the CSPRNG to ensure that auto-registration cookies cannot be tampered with.
Storing tokens in the database prevents user account from being stolen in case your database is compromised. (Remember that a token is currently equivalent to a password.)
The HTTP-Only cookie prevents XSS attacks that could potentially steal a cookie.
source to share
No, storing the username in a cookie to mark that the user it authorizes is not the correct way, and it is definitely insecure.
It would be pretty easy to edit the cookie to be a different username, and voila! you are now logged in as this user.
Instead, you should store some information in a cookie that is not specific to the user, but specific to the user's session. You can create a value from the browser string (scrambled in some way to make it less obvious) and store the value in both a cookie and session data on the server. When the user makes the next request, you can check that the value is from the same session and same browser configuration.
This is of course not completely safe as you can spoof both the cookie data and the browser string, but it is much safer than putting the username in a cookie, and also safer than relying on the session ID alone.
To get authenticity that is truly secure, you must use SSL.
source to share