Why is storing tokens in-memory recommended?

This page recommends storing tokens in memory, but doesn’t explain why. Why is this preferable to localStorage?

Any values stored in memory are still vulnerable to XSS attacks since they’re accessible by JavaScript. Agreed?

2 Likes

Any values stored in memory are still vulnerable to XSS attacks since they’re accessible by JavaScript. Agreed?

Agreed. The main difference is that localStorage makes it even easier to enumerate the contents. The point of this is just to avoid a brute force XSS attack from being able to dump your localStorage somewhere else that could allow it to be used for nefarious purposes. Storing in memory just makes it so someone has to go through the extra effort of targeting your app specifically. But yes, memory is still susceptible to XSS attacks.

There is a certain amount of risk inherent in using SPAs and security. Not storing the tokens is just one good practice to add to others, like limit the duration of the tokens meant for the front-end and also limit the information and permissions that these tokens carry. Or, if your application architecture permits it, keep tokens in the browser and use cookie authentication coupled with a backend.

3 Likes

Apologies, I know this is an old thread but I was wondering if there’s any definitive advantage in transporting the token in the body instead of a header (like authorization), like this page claims

No, transporting tokens in the request body sounds like a bad idea. There a specified HTTP headers for this like the Authorization header which wont be logged by most if not all web/proxy servers.

Anyways, if you are storing your tokens as httpOnly cookies which you should do, there isnt even the option to send the tokens in the request body but instead the tokens will be send automatically by the browser in the Cookie header.

If your client is not a browser but another server side application the tokens should be sent in the Authorization header as it is done in OAuth2.