首页 > 解决方案 > 在 Map 函数中存储会话数据的优缺点

问题描述

谁能解释在(new Map())构造函数中存储会话(敏感)数据的安全缺陷是什么。除非随后关闭浏览器选项卡,否则数据将贯穿应用程序的整个生命周期。根据 MDN,它说所有数据类型都可以存储在其中,所以我猜是否包含二进制数据类型。(只是一个线索)

在我的代码中

class example {
    constructor() {
        this.cache = new Map();
        this.loc = window.location.href;
    }
    async getdata() {
        let data;
        if (this.cache.has(this.loc)) {
            data = this.cache.get(this.loc);
        } else {
            let res = fetch(this.loc);
            if (res.ok) {
                data = res.json();
                this.cache.set(this.loc, data);
            }
        }
        // use data here e.g
        `<span>${data.username}</span>`
        
    }
}

标签: javascript

解决方案


Map 与任何其他数据结构(如对象或字符串常量)相比,没有特定的安全问题。

它们容易受到相同类别的攻击——转储内存、访问全局变量。

我会将它放在一个闭包中,并在应用程序中传递对闭包的引用,以使其对页面上运行的任何其他代码不透明。

有关避免全局暴露状态的更多讨论,请参阅本文:https ://joshwulf.com/blog/2020/02/avoid-global-state/

在构建代码方面,我会使用更多的关注点分离——比如:

class DataCache {
  constructor(href) {
    this.cache = new Map();
    this.loc = href;
  }
  
  async _fetchData() {
    const res = await fetch(this.loc);
    if (res.ok) {
      data = res.json();
      this.cache.set(this.loc, data);
      return data
    }
  }
  
  async getdata() {
    return (this.cache.has(this.loc)) ? this.cache.get(this.loc) : this._fetchData()
  }
}

然后在其他地方进行 DOM 操作。

这样,您的类就更易于测试,尽管它仍然会执行 URL 获取,这是一个副作用。

所以其他东西构造它并传入window.location.href, 调用getdata,然后更新 DOM。


推荐阅读