NodeJS: Where to store client side JWT? sessionStorage, localStorage or cookies?

What is the best place to store JSON Web Tokens for authentication in 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 via JavaScript in the same domain. This means that any JavaScript running on your site will have access to the web store and may therefore be vulnerable to cross-site scripting (XSS) attacks.

localStorage has a different expiration time, sessionStorage will be available only when and through the created window is open. localStorage lasts until you delete it or the user removes it.

Cookies when used with the HttpOnly cookie flag are not accessible via JavaScript and are not XSS responsive. Cookies, however, are vulnerable to sub-forgery (CSRF).

So what is the safest way to store JWT

+7
angularjs authentication cookies jwt
source share
3 answers

sessionStorage: if you want to keep the token until the page is closed. localStorage: for persistent storage. Cookies: Help the token expire after a while.

+1
source share

You can store JWT wherever you want. If you want to protect it, you can encrypt the token and save it in localstorage / cookies; and keep the key in your angularJs application constant. Thus, the token will remain safe and can only be decrypted from your application.

0
source share

DO NOT keep the key in your Angular application as a constant. If you want to safely check the JWT token, extract the JWT from localStorage, send it to the server in the authorization header in the call to $ http.get ().

The key should be available only for viewing or accessing your code on the server. When the server receives the JWT from the authorization header, it can then check if the JWT payload has been changed. If it then returns some authorization error back to the call to $ http.get ().

0
source share

All Articles