Cookies and Sessions: Maintaining Application State
Cookies
HTTP itself does not maintain user state, yet sites often need to recognize users, remember information, or restrict access. Cookies commonly support login persistence so later visits do not require entering a username and password again. This convenience also raises privacy risks, especially on shared computers.
On a first Amazon visit, the response supplies an identifier through Set-Cookie and the browser stores it. Later Amazon requests include that site's stored identifier. Amazon can associate it with shopping-cart state and personalized recommendations.
| Exchange | Browser | Server |
|---|---|---|
| First Amazon request | eBay: 8734 | Set-Cookie: 1678 |
| Store identifier | eBay: 8734; Amazon: 1678 | ID 1678 → database |
| Later Amazon request | Cookie: 1678 | Look up 1678 |
KNOWLEDGE QUIZ
A Cookie Carries an Identifier; a Session Holds State
Set-Cookie tells a browser to store a name and value. Cookie returns applicable values in later requests. Domain, path, expiry, and other rules decide which values apply; the browser must not send every site's cookies to the current site.
A session often stores shopping-cart or login state on the server and places a hard-to-guess session identifier in a cookie. The server uses the returned identifier to find state. This is not putting a password in the cookie or trusting a client to declare itself an administrator. Sessions can expire or be revoked; possessing an old cookie does not mean authorization remains valid.
Watch cookies carry state between browser and servers
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
Scope and Security Attributes
Secure restricts sending to secure connections. HttpOnly restricts script access but does not stop the browser sending the cookie with applicable requests. SameSite restricts some cross-site sending and can reduce cross-site request-forgery risks; it is not complete access control.
The server still validates sessions and authorization. Login normally rotates session identifiers; logout should invalidate relevant server-side state, not merely change a displayed username. A shared computer should not leave one person's valid session available to the next user.
Inspect cookie attributes with Python
Parse the synthetic Set-Cookie value session=1678; Path=/; HttpOnly; Secure; SameSite=Lax using Python's http.cookies.SimpleCookie. Print the identifier and the HttpOnly and Secure flags, expecting 1678, True, True on separate lines. Explain each flag and why none replaces server session validation. Do not use real session tokens.