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?

2 Answers 2


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.

  • Use the secure and httpOnly flags.
  • Encode the session cookie data and cryptographically sign the encoded data with a MAC. Check the signature at the server every time, before bothering to decode the session cookie data. (Rails does this by default.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.