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

AWS Auth Cookie存储未编码加号(+),致Angular项目Cookie删除失败

问题描述

在Angular项目中使用ngx-cookie-service配合AWS Auth时,遇到Cookie编码异常:

  • 我的AWS Auth配置代码:
const config = awsconfig;
config.cookieStorage = { domain: "mydomain", path: "/", expires: 365, sameSite: "lax", secure: true };
  • 正常场景:邮箱arunk@gmail.com生成的Cookie键符合URL编码规范:
    CognitoIdentityServiceProvider.727vitcmg8qrnffc3lmrnb9.arunk%40gmail.com.accessToken
  • 异常场景:邮箱arunk+1@gmail.com生成的Cookie键中,加号(+)未被正确编码,实际生成:
    CognitoIdentityServiceProvider.727vitcmg8qrnffc3lmrnb9.arunk+1%40gmail.com.accessToken
  • 预期正确编码结果:
    CognitoIdentityServiceProvider.727vitcmg8qrnffc3lmrnb9.arunk%2B1%40gmail.com.accessToken
  • 直接影响:加号未编码导致ngx-cookie-service无法正常删除该Cookie。

解决方案

1. 提前编码邮箱地址

在调用AWS Auth相关方法前,手动对邮箱地址做URL编码,确保特殊字符被正确转换:

const rawEmail = 'arunk+1@gmail.com';
// 用encodeURIComponent处理所有特殊字符,包括+和@
const encodedEmail = encodeURIComponent(rawEmail);
// 后续将encodedEmail传入AWS Auth的身份验证流程

如果无法修改AWS Auth的Cookie生成逻辑,可自定义Cookie删除方法,同时兼容编码前和编码后的Cookie键:

import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Injectable({ providedIn: 'root' })
export class AuthCookieService {
  private cognitoClientId = '727vitcmg8qrnffc3lmrnb9';

  constructor(private cookieService: CookieService) {}

  deleteAuthToken(email: string, domain: string) {
    const encodedEmail = encodeURIComponent(email);
    // 构造两种可能的Cookie键
    const unencodedKey = `CognitoIdentityServiceProvider.${this.cognitoClientId}.${email}.accessToken`;
    const encodedKey = `CognitoIdentityServiceProvider.${this.cognitoClientId}.${encodedEmail}.accessToken`;
    
    // 同时删除两种键,确保覆盖异常场景
    this.cookieService.delete(unencodedKey, '/', domain, true, 'Lax');
    this.cookieService.delete(encodedKey, '/', domain, true, 'Lax');
  }
}

3. 调整AWS Auth的编码策略

检查AWS Amplify/Cognito SDK版本,部分版本需手动配置强制严格URL编码。可以尝试在初始化Auth时,添加编码相关配置项,确保所有特殊字符(包括+)都被转换为标准URL编码值。

内容的提问来源于stack exchange,提问作者Arun Kenjila

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:45:01