Storing tokens in single-page applications

Single-page applications that use tokens to authenticate users need to implement a strategy for storing the tokens securely.

Don't use localStorage

Tokens should not be stored in localStorage or sessionStorage. These data stores are accessible from any JavaScript code running on the page. Storing tokens in localStorage makes your application vulnerable to XSS attacks.

You might think you control all the JavaScript on a page, but that's not necessarily true. A dependency of a dependency, a 3rd party tracking script, or a chrome plugin are all examples of code that could be malicious without your knowledge.

Don't use browser cookies

Tokens should not be stored in cookies created with JavaScript. JavaScript cookies, similarly to localStorage, can be read by other JavaScript code.

Malicious code running on the client could access the token and make requests on behalf of the user.

Do use memory

Storing a token in memory is better than saving a token in localStorage, as long as it isn't stored in variable accessible by the global scope.

The problem with storing tokens in memory is that the storage isn't persistent when a user refreshes the page or opens your application in a new browser tab.

Do use HTTP cookies

Tokens can be stored in cookies created by the server as long as it has the correct security attributes.

A cookie storing a token should have the HttpOnly attribute. This attribute ensures it cannot be read with JavaScript, thus protecting against XSS attacks.

The cookie should also have the Secure attribute. This attribute ensures the cookie can only be set and read on HTTPS connections. Using an encrypted connection protects against man-in-the-middle attacks.

The Domain attribute should be used to ensure that the cookie is only returned to the server of the application.

Lastly, the SameSite attribute should be either Strict or Lax. This attribute ensures that only the server can store the cookie, which protects against CSRF attacks.

For this method to work, the client and server applications must be hosted on the same domain.

Authentication scaffolding

Starter kits for Laravel, Vue and React.