DEV Community

Storing tokens in single-page applications

Bjørn Lindholm on August 26, 2020

Single-page applications that use tokens to authenticate users need to implement a strategy for storing the tokens securely. Don't use lo...
Collapse
 
gregorip02 profile image
Gregori Piñeres

Please don't use localStorage 🙅🏾‍♂️🙅🏾‍♂️🙅🏾‍♂️🙅🏾‍♂️🙅🏾‍♂️

Collapse
 
omaratta212 profile image
Omar Atta

With Http-only you are still vulnerable to self-XSS, any browse extension, for example, could send requests to your server as the authenticated user. How should we deal with it?

Collapse
 
paularah profile image
Paul Arah

Embed CRSF tokens your Auth tokens payload and also save the CSRF tokens in local storage. Then on the server, verify the CRSF token in the payload against the CRSF token retrieved from local storage. This completely isolates you from both types of attack.

Collapse
 
ndiuel profile image
ndiuel

You pray to your God for protection.

Collapse
 
miladr0 profile image
Milad Ranjbar

actually ur vulnerable to CSRF, if using the cookie with HTTP-only but u can use a package csurf to solve this problem.

Collapse
 
bjornlindholmdk profile image
Bjørn Lindholm

That's a tricky one. One way could be to store the cookie in memory with a limited scope

Collapse
 
boussou profile image
Nadir Boussoukaia • Edited

"JavaScript cookies, similarly to localStorage, can be read by other JavaScript code." => that is wrong. You have to use cookies.

I suppose you call "HTTP cookies" cookies that are generated by the server: right. With the secure flag.

Collapse
 
bjornlindholmdk profile image
Bjørn Lindholm

Yeah that what was I was trying to explain. JavaScript cookies in this case are cookies set by document.cookie while HTTP cookies are cookies set by the server. Sorry for confusion!

Collapse
 
robencom profile image
robencom

Where should I save my token and user data in a Vue-Laravel app??
Coming from a PHP background, PHP saves such info in the session, which is a file in the server. Now that I am doing the front-end with Vue, I'm keeping the token on the localstorage (the app is still in dev) until I find a better solution.
For the user data, I am making an axios call, but I really don't like that, because it is an extra axios call for every page.

Kindly suggest the best way to do this?

Collapse
 
anandkashyap profile image
Anand Kashyap

Any way to have client and server have same domain but keeping them hosted separately?

Collapse
 
paularah profile image
Paul Arah

that's are a tricky one, does having client and server hosted under different sub-domains of the same domain counts? If yes, then the DNS records just need to point to the different IP addresses of the host. If no, then you might want to configure a reverse proxy to route the traffic based on the URL path to either the client or server. That feels hacky already :)