Differences between cookie, session and Web Storage?

HTTP is a stateless protocol, but there are many situations where we need to get stateful infomation…Cookies were designed for this to be a reliable mechanism for websibites to remember stateful information.

A cookie is a small piece of data sent from a website and stored in the user’s web browser while the user is browsing.

Expires & Max-Age

  • Expires defines a specific date and time when the user agent should delete the cookie, with the format Wdy, DD Mon YYYY HH:MM:SS GMT.
  • If Expires defines a date in the past, the user agent will delete it right away.
  • Max-Age defines the cookie’s expiration as an interval of seconds in the future relative to the time the browser received the cookie.
  • Cookies without Expires and Max-Age will be set as session cookies, it will be deleted after the user closes their user agents (browser).

Domain & Path

  • Domain and Path define the scope of the cookie. If not specified by the server, they default to the domain (not including sub domains) and path of the requested resource.
  • Domain can only be set on the current resource’s top domain and its sub domains.

Secure & HttpOnly

  • Secure and HttpOnly are flags indicating the behaviors the cookie should be enabled.
  • Secure defines whether the cookie communication should be limited to encryted transmission (HTTPS), directing user agents to use cookies only via secure/encrypted connections.
  • HttpOnly directs the user agent not to expose cookies through channels other than HTTP(S) requests. If enabled, the cookie cannot be accessed via client-side scripting languages (JavaScript), which can avoid XSS partly.

Limit

The user agents should provide:

  • at least 4096 bytes per cookie
  • at least 50 cookies per domain
  • at least 3000 cookies total

How

Add fields in HTTP header.

  1. Server :arrow_right: User Agent

    1
    Set-Cookie: key=value[; Expires=date][; Max-Age=seconds][; Domain=domain][; Path=path][; Secure][; HttpOnly]
  2. User Agent :arrow_right: Server

    1
    Cookie: key=value

A web page may contain images or other components stored on servers in other domains (advertisements or something). Cookies that are set during retrieval of these components are called third-party cookies. These cookies can be used to track a user across multiple sites by advertsing companies (where they placed the advertising components).

Example

Cookies Theft && Session Hijacking

  • Network Eavesdropping (Man-in-the-Middle Attack)
  • DNS Cache Poisoning (publishing false sub-domain)
  • XSS (Cross-Site Scripting)
  • CSRF (Cross-Site Request Forgery)

Details in the future. :joy:

Session

Sessions are server-side files / data that contain user information. Sessions have a unique ID that maps them to specific users. This ID can be passed in the URL or saved into a session cookie.

Session ID

A session token is a unique identifier that is generated and sent from a server to a client to identify the current interaction session. The client usually stores and sends the token as an HTTP cookie and/or sends it as a parameter in GET or POST queries.

The reason to use session tokens is that the client only has to handle the identifier—all session data is stored on the server (usually in a database, to which the client does not have direct access) linked to that identifier.

Web Storage

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

  • sessionStorage maintains a separate storage area for each given origin that’s available for the duration of the page session (as long as the browser is open, including page reloads and restores)
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

Usage

1
2
3
4
5
6
7
window.addEventListener('storage', (e) => console.log(e))
localStorage.setItem('local', 1)
localStorage.getItem('local') // 1
localStorage.removeItem('local')
localStorage.getItem('local') // null
localStorage.clear() // remove all items

Differences

Cookie Session localStorage sessionStorage
Where Client Server Client Client
How HTTP Header / JS Session ID - -
API document.cookie Depend on server Web Storage API Web Storage API
Size >= 4KB no limit (Server) Vary between browsers
Expire expires & max-age Page duration Forever (removeItem / clear) Page duration

References

  1. Differences between cookies and sessions?
  2. What is the difference between localStorage, sessionStorage, session and cookies?
  3. HTTP cookie - Wikipedia :bangbang:
  4. HTTP State Management Mechanism - Wikipedia
  5. Session (computer science) - Wikipedia
  6. Session ID - Wikipedia
  7. Web_storage - Wikipedia
  8. Web Storage Support Test
Comments