QA Interview Hub · Knowledge base · Quizzes · Українська

QA Fundamentals › Web and client-server

Cookies vs localStorage vs sessionStorage

Cookies go to the server automatically, so they face CSRF, while any script on the page can read localStorage and sessionStorage, so XSS steals from them. HttpOnly stops scripts reading a cookie, Secure limits it to HTTPS, SameSite restricts cross-site requests. But HttpOnly does not remove XSS: a script can still send requests as the user. QA checks cookie attributes and that cross-site requests are rejected.

QA Fundamentals · Web and client-server

The session token sits in localStorage. Is it a bug or a normal decision?

In a code review or a bug report you hear: "a token in localStorage is dangerous, keep it in a cookie". Another developer answers: "a cookie is vulnerable to CSRF, and localStorage is not". Both are right, and that is why the word "safer" is not enough for a tester. This lesson is about what each storage protects from, what it does not, and which checks follow. The general difference between cookies, localStorage and sessionStorage is covered by the lesson about storages, and here it is about security.

How it works and why. There are two main threats. XSS: a malicious script got onto the page (through an unescaped field or a compromised library) and runs with the page's rights. It can read localStorage, sessionStorage and any cookie without HttpOnly. CSRF: another site makes the user's browser send a request to your application; the browser adds the cookie by itself, so the server considers the request legitimate. Hence different risk profiles.

Two ways to store a token, two risk profiles

HttpOnly cookie

A script cannot read the token

Stealing the token through XSS is harder. But the browser adds the cookie to every request automatically, so protection against CSRF is needed (SameSite, a token, an Origin check).

localStorage

The browser does not add the token by itself

Another site cannot trigger a request with your token, so classic CSRF does not work. But any script on the page reads the token, and XSS steals it.

Figure 1. This is not "safe and unsafe" but a different trade: both options need extra measures, and the choice depends on the team's threat model.

A cookie has attributes, and these are what QA checks:

AttributeWhat it protects fromHow to check
HttpOnlyReading the cookie from a script (theft through XSS)The flag is set in Application; document.cookie does not show it
SecureTransfer over plain HTTPThe flag in Application; the cookie does not go to an http address
SameSite=Lax or StrictSending the cookie in cross-site requests (CSRF)The attribute in Application; a request from another site goes without the cookie
Max-Age or ExpiresA session that is too longThe lifetime in Application matches the requirement (idle and absolute)
Domain and PathA scope that is too wideWithout Domain the cookie belongs only to this host; Path is no wider than needed

SameSite=None allows cross-site sending, and modern browsers require Secure for it. If the attribute is not set, browsers usually treat it as Lax, but an explicit value is more reliable. The __Host- prefix in the name makes the browser accept the cookie only with Secure, Path=/ and without Domain.

Example: from "everything works" to a finding. Functionally, sign-in works. The security check takes two minutes. We sign in, open the page Console and try what a malicious script could do:

// The page Console, after sign-in
document.cookie
// "sid=9f2c...; theme=dark"   <- the session cookie is visible to scripts: no HttpOnly
localStorage.getItem('token')
// "eyJhbGciOi..."              <- the token is available to any page script

Both values can be read, so a script that gets onto the page will steal them. The finding is written up as a defect with a risk, without drama:

Title: [Security] The session cookie has no HttpOnly and SameSite, the token is duplicated in localStorage
Actual: Set-Cookie: sid=9f2c...; Path=/ ; document.cookie returns sid;
  localStorage has the key token with a JWT value
Expected: Set-Cookie: sid=...; Path=/; Secure; HttpOnly; SameSite=Lax
  (the security requirement, the "Sessions" section); the token is not duplicated in storage
Risk: with an XSS a script could steal the session and the token
Severity: major (my conclusion; the security team makes the final assessment)

Why severity "major" and not "critical": the flags alone give no exploit, it needs an XSS too. But they remove the barrier that was meant to limit its consequences. The decision on severity and priority is left to the security team: QA records the fact, the conditions and the risk.

The remaining checks of this topic:

  • What lies in localStorage and sessionStorage: tokens, passwords, full profiles, personal data.
  • After logout all of it is removed, and an old token or cookie gives 401 (details in the lesson about storages).
  • A request that changes data (POST, PUT, DELETE) from another origin or without an Origin check or a CSRF token is rejected (403 per the contract).
  • Sensitive values do not get into the URL (browser history, logs, the Referer header).
  • The session has reasonable idle and absolute lifetimes, and after a password change old sessions stop being valid.

Limits and alternatives. Neither option saves from XSS: a script on the page can send requests on behalf of the user while the page is open, even without reading the token from an HttpOnly cookie. HttpOnly only keeps the token from being carried off and used elsewhere. So the main defence is not to allow XSS (escaping, CSP, updating dependencies), and the storage only reduces the damage. A common approach for single-page applications: a short-lived access token in page memory and a refresh token in an HttpOnly cookie with SameSite, but the final configuration is set by the architecture and the threat model. CSRF must not be confused with CORS: CORS decides what the browser lets a page from another origin read, while the request itself still reaches the server, so it does not protect from CSRF. Finally, browser policies on third-party cookies change and differ between browsers, so for embedded widgets and cross-site scenarios they are checked in several browsers.

Common mistakes.

  • Declaring that "localStorage is unsafe and a cookie is safe" or the other way round: each option has its own vulnerability and its own mitigation.
  • Treating HttpOnly as protection against XSS in general: it protects only from reading the value.
  • Checking a cookie only for presence and not for attributes.
  • Forgetting to check that a dangerous action from another origin is really rejected by the server.
  • Putting a description without conditions and risk into a report: "the cookie is wrong" tells the developer nothing.

Check yourself

The token lies in an HttpOnly cookie. Does it mean XSS is no longer a threat?

Answer

No. A script cannot read the token or carry it away, but it can send requests on behalf of the user while the page is open, because the browser adds the cookie itself. HttpOnly reduces the damage and does not remove the cause.

Why is a token in localStorage not vulnerable to classic CSRF?

Answer

Because the browser does not add it to requests automatically: the token must be added by the application's own script, and another site cannot see the localStorage of a different origin. But the same token is read by any script on the page, so it is vulnerable to XSS.

A cookie is set with SameSite=None but without Secure. What will probably happen?

Answer

Modern browsers will reject such a cookie, because SameSite=None requires Secure. The test: check in Application that the cookie is really stored and that it has Secure when cross-site sending is needed.

In an interview. Junior: Cookies are sent to the server with every request, hold up to 4 KB and can be HttpOnly, Secure and SameSite. localStorage holds about 5 MB with no expiry, sessionStorage lives while the tab is open. Session tokens are better kept in an HttpOnly cookie than in localStorage. Middle/Senior: I consider two threats: XSS and CSRF. HttpOnly stops a script from reading the cookie, but the browser adds it automatically, so SameSite or a CSRF token is needed. In localStorage the token is not added by itself (CSRF does not work), but any script reads it, so XSS steals it. No storage replaces protection against XSS. I test the cookie attributes, the contents of the storages, the behaviour after logout and the rejection of cross-site requests that change data, and I describe the risk in a report without exaggeration.

More articles in this chapter