Some cookie security pit fall to avoid while web development.

When you are doing web development there is a good chance you might forget some of the small security practices about cookies which may cause security issues or data leaks. So I am listing some of the basic points which need to be taken care of while doing development.

Usually, When users log into your web application you authenticate the user and create a cookie to store the user session. But you have to very careful to not store sensitive information about the user like password or credit card information in the cookie because that cookie gets stored in the user's browser. The other thing is that cookie gets send with every request to your server and you don't want to send some sensitive information back and forth when it is not necessary.

The cookie is stored in the user's browser if the user is a little bit tech-savvy. The user can easily modify the cookie data and cause havoc. Let me give you an example.

Let's say when you authenticate to uses in your web app you store UserID in a cookie so in future requests you can use that value to identify which user is making the request. For example, let's say the UserID is 100. The malicious user can easily try to change that value 101 or any other value. If you have a user with that ID then the malicious user can pretend to be some other user and cause many problems.

To avoid this problem you must use sign your cookie before sending it to the user. So when the user makes a change to the value. Your server will be able to detect it because the cryptographic signature will not match. You can use either RSA or ECDSA algorithms.

Sometimes you can just get away with just signing cookie data but you want to make it more secure you can use asymmetric encryption with digital signing. So first you encrypt the data with any asymmetric encryption and then you sign that data before sending it to the browser.

Set expiration Date

You can make a cookie's expiration date as long as you want. But instead of that doing that put the appropriate expiration time on the cookie. Because when the expiration time passes the browser discards the cookie. That will make sure our data in cookies will not be dangling around even when it is not needed.

The one piece of advice would give is not to implement cookie management from scratch unless you have to because of all the modern frameworks and language supports. The best thing about using the cookie library is that it is most likely to be managed by a community of security experts and they will make sure that there is no a security issue with the library. But if you developed the whole signing and encryption why yourself that it will be your responsibility to maintain security fixes.

You can in details about cookie here