Web Development – Best Practices for Cookie-Based Web Authentication

http-responseweb-applicationsweb-development

I'm working on a small side project using CGI and Python (scalability is not an issue and it needs to be a VERY simple system.)

I was thinking of implementing authentication using cookies, and was wondering if there were any established best practices.

When the user successfully authenticates, I want to use cookies to figure out who is logged on. What, according to the best practices, should be stored in such a cookie?

Best Answer

Best case: A single ID that relates to all the other information you need, which in turn is stored in a database.

There are times when it makes sense to put some other information in there, but they are rare. You always need to ask yourself why, at least five times.

SSL will protect your users from session hijacking but, even then, never store unencrypted sensitive information in a cookie. It is, essentially, stored in plain text on the harddrive.

Finally, and most importantly, protect your user against XSS and CSRF attacks.

XSS protection is generally as simple as being careful where you include Javascript from, because Javascript on another server could be changed without your knowledge, and this Javascript has access to cookie data. So if you're using Evil Corp's content-delivery network to serve your jQuery script, they can suddenly add code to send them your users' cookies. You wouldn't know; your users wouldn't know.

Either download scripts and serve them from your own server or use very well-trusted CDNs such as Google or Yahoo.

CSRF protection is usually done by having a random value in a hidden field in a form. The value is kept in the session so that when the form is resubmitted, you can verify it came from the same computer.

Most web frameworks now have very simple techniques for including that token.

Related Topic