DEV Community

Should save acees token in local storage?

Ronald on March 30, 2019

Hi everybody! First I apologise if my English is not the best. It's not my native language. This is my first post, it's 3 am and I cannot sleep t...
Collapse
 
oieduardorabelo profile image
Eduardo Rabelo • Edited

i recommend this article as a reading:

Please Stop Using Local Storage
rdegges.com/2018/please-stop-using...

its author is a bit rough but the section "Sensitive Data" describes one secure way to store/use client-side tokens in spa,

tl;dr: create a crypto signed session identifier cookie in the server, set httpOnly flag to prevent the browser to read any cookie data, use SameSite=strict; secure=true cookie's flag, for every subsequent client-side request you need to send the fetch credentials to the server, on the server you extract/decode the cookie and retrieve any sensitive information

Collapse
 
oieduardorabelo profile image
Eduardo Rabelo • Edited

another good one is:

Using Rails Session Cookies for API Authentication
pragmaticstudio.com/tutorials/rail...

tools/stack aside, its a well written article about API Access Token/Client Side App (coincidently is in Vue too), first he store it in the localStorage, explains the drawbacks and change it to use the Signed Session/HTTP Only (same solution as the article above)

Collapse
 
rmirandasv profile image
Ronald

Thank you! Both posts were excellent!

Collapse
 
joshualjohnson profile image
Joshua Johnson

Hey Ronald,

I wouldn't go about storing tokens in Local Storage. Instead you will want to look into storing the token as an encrypted cookie. Both encrypted by your and decrypted by your PHP application.

So once a user authenticates, send a set-cookie header back with the successful authentication. This cookie will be an encrypted json object that will include an accessToken. So any request made back to the PHP application will send that cookie. If that cookie is present, have the PHP application attempt to decrypt it. If successful then use that token to validate the user.

DO NOT USE LOCAL STORAGE. As that tends to stay around forever.

Collapse
 
rmirandasv profile image
Ronald

Thank you! I will try Cookie's approach!

Collapse
 
reegodev profile image
Matteo Rigon

If you talk to a stateless api there is no alternative than to save them to local storage. Although the posts Eduardo linked are correct, if you read through the comments you'll find that there is really no other ways for SPAs to keep someone logged in. Just make sure your access tokens are short-lived and that they can be revoked

Collapse
 
jamesmh profile image
James Hickey

In this scenario, an httpOnly cookie is probably best. Otherwise, you leave the potential of the JWT/token being read on the client by a script, etc.

Collapse
 
rmirandasv profile image
Ronald

You are right! After reading more about these finally understand that storing token in local storage it's a security issue!!