Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not store JWT in global variable?

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.

like image 235
gaurav5430 Avatar asked Mar 01 '19 11:03

gaurav5430


2 Answers

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.
like image 187
Guerric P Avatar answered Oct 22 '22 06:10

Guerric P


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

like image 38
Ajay Avatar answered Oct 22 '22 06:10

Ajay