Secure Cookies in 5 steps

Published 2/11/2021

This article is part of a series:

Even with the right CORS setup and CSRF protection cookies present a few more attack vectors. Let's discover how to secure cookies.

Note that frameworks usually come with the below settings set properly so even developers inexperienced with web security can develop secure apps.

1. Samesite attribute

We've already covered this topic previously. You want to make sure your cookies are set to sameSite=Lax so they are only being passed when the request comes from the same site, and not a third-party context.

2. HttpOnly attribute

Cookies, by default, can be accessed using javascript via document.cookie. You can imagine this being a problem if an attacker finds a vulnerability to execute arbitrary javascript on your site (more on that in the next article).

To avoid cookies being accessible via JavaScript, set the HttpOnly flag.

3. Secure attribute

By setting the secure attribute, the cookie will only be sent over HTTPS. This is especially important if a user uses your service in a public network where non encrypted traffic can be read by an attacker.

4. Encryption

You can have all of the above set, but if you forget to encrypt your cookies, it can be very dangerous.

Say you don't store a token, but the user ID for the auth cookie. If it's not encrypted, an attacker can just change the cookie value to another user id by himself. To avoid this, the cookie should be encrypted with a strong algorithm like AES-256 and a long, secret, random key.

In Node.js for example, you can use Node's crypto library for this.

Note that encryption is different from hashing (like you would with a password using tools like bcrypt). Encryption allows decrypting the value again which is necessary for cookies.

For extra security, sign cookies using a message authentication code (MAC) to make sure nobody can tamper with it.

This is again possible with the crypto library in Node.js, but generally, for this and all above, I advise you to use something more high level and not implement any of this from scratch.

We've covered a lot in these articles but there are still ways an attacker can steal your users' data through the browser, even though you followed all the protections so far, and that's through XSS attacks. Let's cover this next time and see if React/Vue REALLY protect you from all XSS attack vectors!