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

标签 javascript redux jwt

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

编辑:

我试图找到更多关于存储 token 的信息。似乎所有的文章和答案实际上都是在确定有 2 种方法可以做到这一点后开始讨论的,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

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

最佳答案

如果您将 JWT 存储在全局变量或全局上下文中可用的任何存储中,它会暴露给同一页面上的所有 JS 代码。 如果您信任页面的所有其他 JS 脚本,并且可以保证您的页面不会受到代码注入(inject)攻击,那么将 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.

关于javascript - 为什么不将 JWT 存储在全局变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944009/

相关文章:

javascript - 为什么要将 Redux Action 创建者返回的 Action 括在括号中?

javascript - 飞行前响应中的 Access-Control-Allow-Methods 不允许方法 PATCH

react-native - connect() 中的 mapStateToProps() 必须返回一个普通对象,而不是收到 Undefined

json - 安全和无状态的 JWT 实现

javascript - ag-grid api是否支持列过滤下拉

javascript - html 内容中的 css 链接在加载 html 时抛出错误

symfony - 401 未找到 JWT token

安卓刷新 token

javascript - 使用 jquery 显示两个数据透视表

javascript - 如何在 JavaScript 中将字符串日期数字转换为日期时间?