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

AWS AppSync中ctx.identity.username为空问题求助

解决方案:AppSync Lambda解析器中ctx.identity.username为null的问题

1. 检查AppSync API身份验证配置

  • 确认AppSync API已将Cognito用户池设为身份验证提供者,且启用该身份验证类型。
  • 验证客户端请求AppSync时,是否正确携带有效Cognito ID Token,排除token过期、无效的情况。

2. 修正Lambda数据源权限与配置

  • 对于关联agentPublishEvent mutation的Lambda数据源,确保AppSync被授予调用Lambda的权限,同时Lambda执行角色具备读取Cognito身份信息的权限。
  • 在CDK配置中,将Lambda数据源的invokeWithCredentials属性设为true,这是AppSync向Lambda传递身份信息的关键开关:
    const lambdaDataSource = api.addLambdaDataSource('AgentPublishEventDS', lambdaFunction, {
      invokeWithCredentials: true,
    });
    

3. 调整解析器请求映射模板

  • 打开agentPublishEvent mutation的请求映射模板,显式将身份信息传递给Lambda:
    {
      "version": "2017-02-28",
      "operation": "Invoke",
      "payload": {
        "input": $util.toJson($ctx.args),
        "identity": $util.toJson($ctx.identity)
      }
    }
    
  • 确保模板未过滤或遗漏ctx.identity字段,保证身份信息完整传递。

4. Lambda函数中正确读取身份信息

  • 若通过映射模板传递身份信息,直接从Lambda事件的payload.identity中读取,示例Node.js代码:
    exports.handler = async (event) => {
      const username = event.identity?.username;
      // 使用username写入DynamoDB逻辑
    };
    
  • 若依赖Lambda的context对象,需确保invokeWithCredentials为true且客户端携带有效token,此时context.identity才会被填充。

5. 验证Cognito身份池与用户池关联

  • 检查Cognito身份池是否与目标用户池正确关联,确认身份池的认证提供者列表包含该用户池,且应用客户端ID配置正确。
  • 通过前端调试工具查看请求中的token内容,确认用户登录后Cognito返回的身份ID和用户池信息有效。

6. 排查CDK部署的Schema与API配置

  • 查看cdk-infrastructure/lib/agent-api/schema.graphql中agentPublishEvent mutation的权限规则,确保启用Cognito用户池权限:
    type Mutation {
      agentPublishEvent(input: AgentPublishEventInput!): AgentPublishEvent
        @aws_cognito_user_pools
    }
    
  • 检查CDK中AppSync API的创建代码,确认身份验证提供者配置正确:
    const api = new appsync.GraphqlApi(this, 'AgentApi', {
      name: 'AgentApi',
      schema: appsync.SchemaFile.fromAsset(path.join(__dirname, 'schema.graphql')),
      authorizationConfig: {
        defaultAuthorization: {
          authorizationType: appsync.AuthorizationType.USER_POOL,
          userPoolConfig: {
            userPool: userPool,
          },
        },
      },
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:03:10