为什么不将JWT存储在全局变量中?

时间:2019-03-01 11:45:47

标签: javascript redux jwt

我试图了解将jwt存储在本地存储(易于xss)与cookie(易于csrf)的安全隐患。如果我将jwt令牌存储在前端的应用程序状态(例如在redux存储区中),那么我想了解安全隐患。

编辑:

我试图找出有关存储令牌的更多信息。似乎所有文章和答案实际上都是在确定有两种方法(cookie或浏览器存储)后才开始进行讨论的。 像这个相关的问题: Where to store JWT in browser? How to protect against CSRF? 像这些帖子: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage https://auth0.com/docs/security/store-tokens

我了解其中大多数的要点,但是我试图明确讨论全局变量的选项。

2 个答案:

答案 0 :(得分:2)

根据我的理解,将JWT存储在浏览器本地存储/缓存中更多地是关于通过浏览器会话持久保存令牌(用户授权)。

答案 1 :(得分:2)

如果将JWT存储在全局变量中,或在全局上下文中可用的任何存储中,则JWT会在同一页面上显示给所有JS代码。 如果您信任页面上的所有其他JS脚本,并且可以保证页面不受代码注入攻击的影响,那么可以安全地将JWT存储在全局变量中。

如果您不能保证JWT是安全的,请不要使用全局变量,而应使用像这样的封装:

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