8
votes

What is the best place to store JSON Web Tokens for authentication on a SPA with NodeJS and (for example) AngularJS?

What I got so far:

Possible places:

  • HTML5 Web Storage (localStorage/sessionStorage)
  • Cookies

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks.

localStorage has a different expiration time, sessionStorage will only be accessible while and by the window that created it is open. localStorage lasts until you delete it or the user deletes it.

Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. However, cookies are vulnerable to cross-site request forgery (CSRF).

So what is the most secure way to store JWTs

3
I provided an answer on this topic to a related question that may have useful additional information about all the possibilities.João Angelo

3 Answers

0
votes

Do NOT keep the key in the Angular app as a constant. If you want to securely validate the JWT token, retrieve the JWT from localStorage, send it off to the server in an Authorization header in a $http.get() call.

The key should only be viewable / accessible by your code on the server. When the server gets the JWT from the Authorization header it can then check if the JWT payload has been tampered with. If it has then return some sort of authorization error back to the $http.get() call.

0
votes
  • sessionStorage: If you want the token to be stored till the page is closed.
  • localStorage: For persistent storage.
  • cookies: Help the token to expire after a period of time.
-2
votes

You can store the JWT anywhere you want. If you want to secure it you can encrypt the token and store it in localstorage/cookies and keep the key in your angularJs app as a constant; the token will remain safe and only can be decrypted from your app.