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

如何反序列化从Cognito属性获取的GUID ID数组

解决Cognito自定义属性无引号UUID数组的反序列化问题

你遇到的问题是Cognito映射第三方声明后返回的自定义属性值不符合标准JSON格式——数组内的UUID没有被双引号包裹,导致反序列化工具无法识别。以下是几种可行的解决办法:


1. 预处理字符串为标准JSON格式

直接对拿到的属性字符串做正则替换,给每个UUID添加双引号,再进行反序列化。这是最快速的临时解决方案:

C# 示例

using System.Text.Json;
using System.Text.RegularExpressions;

string cognitoAttrValue = "[bf5ad010-8961-49d7-b068-87f23026f49d,\n0080d0fe-6a19-4dfe-a472-09a3f93d7015]";
// 匹配UUID格式并添加双引号
string validJson = Regex.Replace(cognitoAttrValue, @"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})", "\"$1\"");
List<string> uuidList = JsonSerializer.Deserialize<List<string>>(validJson);

Python 示例

import re
import json

cognito_attr_value = "[bf5ad010-8961-49d7-b068-87f23026f49d,\n0080d0fe-6a19-4dfe-a472-09a3f93d7015]"
valid_json = re.sub(r'([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})', r'"\1"', cognito_attr_value)
uuid_list = json.loads(valid_json)

2. 直接解析非标准格式字符串

跳过JSON反序列化,手动提取数组内的UUID值:

C# 示例

string cognitoAttrValue = "[bf5ad010-8961-49d7-b068-87f23026f49d,\n0080d0fe-6a19-4dfe-a472-09a3f93d7015]";
// 去除首尾括号,分割内容并清理空白
string[] uuidArray = cognitoAttrValue.Trim('[').Trim(']')
                                     .Split(new[] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(s => s.Trim())
                                     .ToArray();

Python 示例

cognito_attr_value = "[bf5ad010-8961-49d7-b068-87f23026f49d,\n0080d0fe-6a19-4dfe-a472-09a3f93d7015]"
# 提取括号内内容,分割后去重空白
inner_content = cognito_attr_value.strip('[]')
uuid_list = [uuid.strip() for uuid in inner_content.split(',') if uuid.strip()]

3. 从根源修正Cognito映射规则(推荐)

通过Cognito的Pre Token Generation Lambda触发器处理属性值,确保存入自定义属性的是标准JSON格式:

Node.js Lambda 示例

exports.handler = async (event) => {
    // 获取第三方声明中的原始UUID数组(假设为数组类型)
    const rawUuidList = event.request.userAttributes['custom:target-attribute'];
    // 转换为标准JSON字符串并覆盖属性值
    event.response.claimsOverrideDetails = {
        claimsToAddOrOverride: {
            'custom:target-attribute': JSON.stringify(rawUuidList)
        }
    };
    return event;
};

配置该触发器后,用户登录时Cognito会自动将属性值格式化为带引号的JSON数组,后端无需额外处理即可正常反序列化。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:45:42