Cookie & Session Review

1. Cookie

  • Cookie is set via response header.
  • Also, it is shipped back with request header.


2. Session

  • Session uses Cookie in most situations.
  • Session will set a cookie to store the Session id.
  • When the Cookie is sent back to server, our server will find the correspondent Session.
  • Many third party modules in many different languages have sealed up above functionalities for us.
  • Session is by default stored in server’s memory, and we could also store Sessions in file or database


3. Cookie Configuration, “Set-Cookie” in Response Header

There are some properties could be configured in “Set-Cookie”:

  • cookie_name=cookie_value;
  • Expires=Sun, 9 Jan 2019 21:47:26 GMT; It should follow http-date format.
  • Max-Age=85; Another way to set expire time, unit is second, has higher priority than “Expires”.
  • Domain=www.yourserverdomain.com; It means each time when you visit www.yourserverdomain.com that this Cookie will be send with request.
  • Path=/; “/” and its children paths can use the Cookie.
  • Secure; Cookie can be only transferred via https.
  • HttpOnly; Cookie can be only used via http/https, and cannot be used by Javascript.


4. Session Configuration

There are some properties we shall concern:

  • “secret” This is required option, we use it to sign our Session id, means we encrypt it.
  • Existing time in our server, not required, it always the same with Session id Cookie Max-Age.
  • Store is an important option but not required, Sessions will be stored in server memory by default, but we can change it to be stored in files or database.
  • Proxy. When we use a reverse proxy server like Nginx between our application server and clients, and we need secure cookie, then we need configure this option.


5. Store Session ID in Client Side

There are two ways that app server could give us the Session id:

  • Via Cookie.
  • If someone’s browser forbids Cookie, we can configure our server to rewrite all the urls in pages, add something like ‘?sid=”yoursessionid”‘ as suffix.


Leave a Reply

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