6
votes

I am trying to understand the security implications of storing jwt in local storage (prone to xss) vs cookie (prone to csrf). I would like to understand the security implications if I store the jwt token in my app state in the frontend, like in a redux store.

EDIT:

I have tried to find out more about storing tokens. It seems all the articles and answers actually start the discussion after establishing that there are 2 ways to do that, cookies or browser storage. Like this relevant question: Where to store JWT in browser? How to protect against CSRF? Like these posts: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage https://auth0.com/docs/security/store-tokens

I understand the point of most of these, but I am trying to explicitly discuss the option of global variable.

2
I get that there are a lot of answers discussing about local storage vs cookies, but could not find any which discusses global variable. It might be completely idiotic to do so and that is what I was trying to find out.gaurav5430
The duplicate question linked above does not discuss global variables.gaurav5430
@mplungjan I did try to google it and none of the links actually discussed a global variable. All of them are about cookie vs local storage. I am happy to update the question with this info if that means it can be opened for explanations/answers again.gaurav5430
Yes show what you investigated and your conclusions and why it is not a dupe of stackoverflow.com/questions/27067251/…mplungjan

2 Answers

4
votes

If you store a JWT in a global variable, or any store available from the global context, it is exposed to all of the JS code on the same page. If you trust every other JS script of your page, and if you can guarantee that your page is not vulnerable to code injection attacks, then it's safe to store the JWT in a global variable.

If you can't guarantee that the JWT will be safe, don't use global variables, prefer using encapsulation like this:

(function() {
  // Retrieve the JWT from somewhere
  var jwt = "mockjwt";

  //All of the code that needs the JWT goes here
  console.log('Safe code:', jwt);

  
})();

// Evil code, either:
// - Injected through a vulnerability of your website (e.g: eval misuse,
//   WYSIWYG editor vulnerable to script tag injection, etc...)
// - Injected because your user got fooled by some "copy/paste this code in the F12 tab
//   of your browser, and you'll unlock a secret functionality"
// - Untrusted <script> tag that you added to your website

console.log('Evil code:', jwt);  //Fails because the JWT is scoped to the anonymous
                                 //function and is not accessible from anywhere outside
                                 //the function.
2
votes

As per my understanding, storing JWT in browser local storage/cache is more about persisting token(user authorization) through browser sessions.