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
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.