Cookies and Sessions
Useful Tidbits
- Cookies are interpreted and stored client side
- Sessions are stored server side
- Session ID’s are generated by the server
- Servers can respond with set-cookie in the header
- Browsers will store cookie when response header includes set-cookie
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:
- User makes a post request with log-in information
- Server generates a sessionID
- Server verifies the log-in information is valid
- Server responds with header set-cookie: sessionID
- User client sees resposne header with set-cookie
- User client stores set-cookie value, sessionID
- User client makes get request to server
- Server sees request header contains cookie
- Server sees cookie matches a stored sessionID
- Now the server knows this user has been authenticated!
And that’s one way to handle authenticated user sessions.