Cookies vs. Sessions

Cookies and sessions both store unique information for users. The biggest difference between them is where they are stored; cookies are stored locally on the user’s computer, and sessions are stored remotely on the server that the user is accessing via their web browser. Cookies are good for storing data that isn’t sensitive (items in a shopping cart, username, etc.), but they pose a security threat if the remote server trusts them with important information. For example, storing a username in a cookie is useful for auto-populating a login text field, but that same cookie should not be used to authenticate a logged-in user.

One of the benefits of cookies is that–because they are stored on the user’s computer–the server doesn’t need to store any information, and if there are millions of users, that’s a lot of saved space on the server! This locality is the same reason why it’s not a good idea to authenticate with cookies–they can be modified locally before being sent to the server.

Let’s look at an insecure website for example: Bob Roberts logs in with his username, broberts, and his password. After ensuring that the username and password are valid, the server returns Bob’s account page as expected and stores his username in a browser cookie. When Bob requests another page, the server checks the cookie stored on his computer to see who is logged in, sees that it’s “broberts”, and returns the requested information. Sounds good, right? But what if Bob changed the value of that cookie from broberts to bsmith? If there is another user with that username (let’s say Bill Smith), the page that the server returned to Bob would be from Bill’s account. This is where sessions come in handy.

Instead of storing “broberts” on the local machine, a session ID is stored in a local cookie that can be used to look up the session on the server. So when broberts requests a page, his computer sends the session ID to the server with the request, and the server can look up the session based on the ID that Bob sent and use that to get the username. (It’s important to note that the server is storing other information in the session to make sure that the ID wasn’t tampered with–otherwise it would be easy for Bob to change the session ID.)

This is a very brief overview, so I encourage you to read more about cookies and sessions.  These Wikipedia articles go a much deeper and have information on different types.  If you have any questions, please let me know in the comments below!

Happy coding!
Ryan from The Bunch

Leave a Reply

Your email address will not be published. Required fields are marked *