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

gau*_*430 6 javascript jwt redux

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

编辑:

我试图找到更多关于存储令牌的信息。似乎所有文章和答案实际上都是在确定有两种方法可以做到这一点后开始讨论的,cookie 或浏览器存储。喜欢这个相关的问题: Where to store JWT in browser? 如何防范CSRF? 喜欢这些帖子:https : //stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage https://auth0.com/docs/security/store-tokens

我理解其中大部分的要点,但我试图明确讨论全局变量的选项。

Twi*_*her 6

如果将 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.
Run Code Online (Sandbox Code Playgroud)


Aja*_*jay 2

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