Cookies and Sessions
Lecture Notes for CS142
Winter Quarter 2009
John Ousterhout
- Web application servers are generally "stateless":
- A series of HTTP requests from the same browser appear to the server
as totally independent; it's not obvious that they are all
coming from the same browser or user.
- Typically, Web servers don't maintain any information from request
to request (only information on disk survives from one request to
another).
- Statelessness causes problems for application developers:
need to tie together a series of requests from the same user.
- Solution: browser cookies.
- Cookie: a small amount of data stored by the browser at the request
of a server.
- Whenever the browser sends a request to a server, it also sends
any cookies that are relevant to that server.
- Cookies are transmitted using header fields in the HTTP protocol.
- Cookie lifecycle:
- The first time a browser connects with a particular server, there
are no cookies.
- The server creates a unique identifier, and returns a
Set-Cookie: header in the response that contains the identifier.
- In the future when the browser connects with the same server, it
includes a Cookie: header containing the identifier,
which the server can use to connect related requests.
- What's in a cookie?
- Name and data.
- The size of data is limited by browsers (typically < 4 KB).
- A server can define multiple cookies with different names, but
browsers limit the number of cookies per server (around 50).
- Domain for this cookie: server, port (optional),
URL prefix (optional). The cookie is only included in
requests matching its domain.
- Expiration date: browser can delete old cookies.
- How are cookies used?
- Web server maintains a collection of sessions
- Each session is a pool of data related to an active connection
(one browser instance).
- Typically the cookie for an application contains an identifier
for a session.
- Web frameworks like Rails do most of the work of managing
sessions and cookies.