Last Updated on April 22, 2022
Web applications need to store tokens to help manage user sessions. Because the browser/server relationship is “stateless,” every request would otherwise require reauthentication.
As a web developer, you typically have two options for client-side token storage: local storage (aka localStorage) and cookies. The two have different purposes, and hence different strengths and weaknesses. Cookies are intended to be read by the server, whereas localStorage can only be read by the browser. Thus, cookies are restricted to small data volumes, while localStorage can store more data.
This post discusses whether to use localStorage or cookies for best-practice security of session management tokens in your web apps.
Two token types you need to store
Web applications most commonly need to utilize and store two types of tokens:
- Access tokens, which are short-lived JWT tokens signed by the server and included in every HTTP request that a browser makes to a web server, in order to authorize the request
- Refresh tokens, which are lasting, opaque strings stored in the application database and used to acquire new access tokens when they expire
Either of these tokens can potentially be stored as a cookie or in localStorage. So, which to choose?
localStorage pros and cons
Another advantage of localStorage is its contents cannot be automatically sent anywhere. Therefore, localStorage is immune to cross-site request forgery (CSRF) attacks.
Another potential disadvantage of localStorage is that, as persistent storage scoped to an origin rather than a domain, it cannot be accessed from different domains or even subdomains.
Cookies pros and cons
Both cookies and localStorage are vulnerable to XSS attacks. However, cookie-based token storage is more likely to mitigate these types of attacks if implemented securely. The OWASP community recommends storing tokens using cookies because of its many secure configuration options.
Need to validate the security of your web application? Contact Pivot Point Security to speak with an expert about how application penetration testing services can protect your confidential data, isolate vulnerabilities and provide a fast and affordable way to prove your service is secure.