Single-page applications that use tokens to authenticate users need to implement a strategy for storing the tokens securely.
Tokens should not be stored in
localStorage makes your application vulnerable to XSS attacks.
Malicious code running on the client could access the token and make requests on behalf of the user.
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.
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
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.
Domain attribute should be used to ensure that the cookie is only returned to the server of the application.
SameSite attribute should be either
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.
Tired of handling authentication manually? I'm creating starter kits for Laravel and Vue/React for different authentication methods. Check out Titanium to stay updated!