javascript - 在 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>`
}
}
解决方案
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。
推荐阅读
- android - RecyclerView 适配器`onCreateViewHolder` & `onBindViewHolder` 只调用一次
- java - 如何在实现屏幕录制时隐藏按钮或 textView
- rust - 互斥锁下结构不相交字段的多次借用
- python - 传递无限重复数据集时,您必须指定 `steps_per_epoch` 参数
- graphql - Apollo 客户端是否缓存 React 中的嵌套对象?
- .net - 仅当文件不存在时才使用 PowerShell 从 SFTP 服务器传输文件
- d3.js - 字符串 x 刻度不缩放 D3 中的数据
- ios - WCSession 激活会话不调用委托方法
- javascript - 在函数中作为参数传递时无法设置 css 样式
- python - 我得到一个 IndexError: list index out of range 错误