Cookies and Sessions

Useful Tidbits

For each request a client sends to the server, the client will send the cookies for that site, as part of the header, along with the request. Upon reception, the server generates an unique ID, sessionID, for that user. Unless specified to be save in a database, this sessionID and session object will exist in the server RAM. For persistence, store the session object and ID in a database.

Using Cookies to Store Authenticated Sessions

Suppose a site should only display information to authenticated users, how does the site keep track that the clients making requests is an “authenticated” user?

Typically, a site only requires the user to be authenticated once. After that, the user can browse the site without having to log-in again.

From a server’s perspective, this is achievable by sending the sessionID back to the browser, via the set-cookie option in the response header, when the user is authenticated. From the client’s browser perspective, upon reception of a response header with set-cookie, the set-cookie value, which is the sessionID, will be stored on the client. Next time the client makes a request to the server, this cookie is sent along as part of the request. The server then sees this cookie, which contains a sessionID, and does a look up to see whether this sessionID exists in the server’s local storage or RAM (depending on implementation). If the server already contains this sessionID, then the user has previously been authenticated, and the server is free to respond with the requested information.

The flow of information described above can be simplified to the following:

  1. User makes a post request with log-in information
  2. Server generates a sessionID
  3. Server verifies the log-in information is valid
  4. Server responds with header set-cookie: sessionID
  5. User client sees resposne header with set-cookie
  6. User client stores set-cookie value, sessionID
  7. User client makes get request to server
  8. Server sees request header contains cookie
  9. Server sees cookie matches a stored sessionID
  10. Now the server knows this user has been authenticated!

And that’s one way to handle authenticated user sessions.

Back