首页 > 解决方案 > 如何检查浏览器的 Storage 对象是 localStorage 还是 sessionStorage 来管理客户端中的静态/动态密钥?

问题描述

我设计了一个可装饰的存储服务,其中一个示例类似于getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage()))typescript/javascript。

为了实现getSecureStorage,我使用硬编码的静态密码密钥并加密要添加到本地或会话存储的键/值对的每个值。

由于我们已经将密钥保存在客户端中,因此我决定在每次过期后动态生成密钥,以防止用户以某种方式从源获取密钥并与他人共享该密钥的情况。在这种情况下,我需要为每个不同的键/值存储每个新的 cipherKey。

createSecureStorage(storage: Storage): Storage { 
    var cipherKeyMap = this.keyMapping;
    let privateState = function() {
        let cipherKey;
        this.encrypt = function(key: string, data: string): string {
          let entry = cipherKeyMap.find(entry => entry.key === key);
          if (entry) {
            cipherKey = entry.cipherKey;
          } else {
            cipherKey = Array.from({length: 16}, () => Math.floor(Math.random() * 90));
            cipherKeyMap.push({"key": key, "cipherKey": cipherKey});
          //...
        };

        this.decrypt = function(key: string, data: string): string {
          //...
        };
    }
    let state = new privateState();

    return {
      setItem(key: string, value: string) {
        //...
      },
      getItem(key: string) {
        //...
      },

      //is triggered from expirableSecureStorage
      removeItem(key: string) {
        storage.removeItem(key);
        cipherKeyMap.splice(cipherKeyMap.findIndex(r => r.key === key), 1);
      }
    } 
  }

上面的函数适用于两者localStoragesessionStorage它们的类型为Storage并且也导出为

//lib.dom.d.ts
declare var sessionStorage: Storage;
declare var localStorage: Storage;

此服务将用于来自多个客户端的多个案例,以获取将保存在这些存储中的值。


对于该createSecureStorage功能,我意识到如果传递的存储是localStorage,当用户关闭选项卡/窗口时,应用程序状态将消失,我将丢失密钥,但相关数据将保留在本地存储中,并使用这些密钥加密

我想我必须做其中之一:

  1. 在 localStorage 的情况下管理随机生成的密码密钥的持久性或清除。
  2. 或者仅将使用硬编码静态密码密钥加密的值放入 localStorage,并将通过动态生成的密码密钥加密的值放入 sessionStorage

我选择 #2 是因为我不想在客户端中保留密码密钥,因为我们当前的状态也不是非常安全。

因此,要做到这一点,我认为我需要区分 localStorage 和 sessionStorage。

如何区分 sessionStorage 和 localStorage?

标签: javascriptangulartypescriptlocal-storagesession-storage

解决方案


要确定您传递的对象是否是localStorage,或者sessionStorage您可以只比较它们,因为对象是通过引用进行比较的。

function getStorage(storage){console.log(storage === localStorage)};
getStorage(localStorage);
getStorage(sessionStorage);

推荐阅读