You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular应用中如何移除或加密Cognito存于Local Storage的令牌?

解决AWS Amplify Cognito在Local Storage存储凭证的问题

一、更换存储位置,避开Local Storage

Amplify默认使用Local Storage存储Cognito凭证,你可以通过配置切换到更安全的存储方式:

1. 切换到Session Storage

Session Storage的内容会在标签页关闭后自动清除,不会跨会话留存,比Local Storage风险更低。在Angular项目的Amplify初始化代码中修改配置:

import { Amplify } from 'aws-amplify';
import { Auth } from '@aws-amplify/auth';

Amplify.configure({
  Auth: {
    // 你的Cognito基础配置(用户池ID、客户端ID等)
    storage: window.sessionStorage // 替换默认的localStorage
  }
});

2. 使用内存存储(无持久化)

如果不需要记住登录状态(页面刷新后需重新登录),可以用内存对象作为存储载体,彻底避开浏览器存储:

// 自定义内存存储实现
const memoryStorage = {
  _data: {} as Record<string, string>,
  getItem: (key: string) => this._data[key] || null,
  setItem: (key: string, value: string) => { this._data[key] = value; },
  removeItem: (key: string) => { delete this._data[key]; },
  clear: () => { this._data = {}; }
};

Amplify.configure({
  Auth: {
    // 你的Cognito基础配置
    storage: memoryStorage
  }
});

二、加密Local Storage中的凭证

如果必须保留持久化登录功能,可以通过自定义存储类加密存储内容:

1. 安装加密依赖

使用crypto-js实现加解密:

npm install crypto-js

2. 实现加密存储类

import * as CryptoJS from 'crypto-js';

// 密钥建议通过后端接口动态获取,避免硬编码在前端
const ENCRYPTION_KEY = 'your-secure-encryption-key';

const encryptedLocalStorage = {
  getItem: (key: string) => {
    const encryptedVal = window.localStorage.getItem(key);
    if (!encryptedVal) return null;
    // 解密数据
    const bytes = CryptoJS.AES.decrypt(encryptedVal, ENCRYPTION_KEY);
    return bytes.toString(CryptoJS.enc.Utf8);
  },
  setItem: (key: string, value: string) => {
    // 加密数据后存储
    const encryptedVal = CryptoJS.AES.encrypt(value, ENCRYPTION_KEY).toString();
    window.localStorage.setItem(key, encryptedVal);
  },
  removeItem: (key: string) => window.localStorage.removeItem(key),
  clear: () => window.localStorage.clear()
};

Amplify.configure({
  Auth: {
    // 你的Cognito基础配置
    storage: encryptedLocalStorage
  }
});

三、关键注意事项

  • 内存存储完全避免了浏览器存储泄露风险,但会丢失持久化登录能力,适合对安全性要求极高的场景。
  • 即便用Session Storage或加密存储,仍需做好XSS防护(比如配置CSP策略、过滤用户输入),因为XSS脚本仍可访问这些存储内容。
  • 加密密钥绝对不能硬编码在前端代码中,否则反编译后密钥泄露,加密就失去意义。

内容的提问来源于stack exchange,提问作者Sowmiya C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 11:10:04