首页 > 解决方案 > 如何在 AppSync Resolver 中仅使用 `ctx.identity.cognitoIdentityId` 获取相关的 Cognito 用户池用户数据?

问题描述

早些时候,当我们仅使用 Cognito 用户池开始我们的项目时,我创建了许多通过 Cognito 用户池数据验证的解析器,例如:

#if( $ctx.identity.claims["custom:role"] == "admin" )
...some code...(get data, invoke lambda, e.t.c.)
#else
  $utils.unauthorized()
#end

但后来我们需要其他授权提供商(Facebook、Google 等)。因此,我们迁移到 cognitoIdentityId,但在 AppSync 解析器中从 Cognito 用户池获取用户数据时出现问题。在 AWS Lambda 中,我通过 cognitoIdentityAuthProvider找到UserAttributes了 Cognito 用户池 ID,并且可以获取 Cognito 用户属性,如下所示:

...
...
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({
  apiVersion: '2016-04-18',
});

const getCognitoUserPoolId = (authProvider) => {
  const parts = authProvider.split(':');
  return parts[parts.length - 1].slice(0, -1);
};

// cognitoIdentityAuthProvider, which we pass as an parameter($ctx.identity.cognitoIdentityAuthProvider) from the AppSync resolver
const SUB = getCognitoUserPoolId(cognitoIdentityAuthProvider);

const params = {
  UserPoolId: COGNITO_USER_POOL_ID,
  Username: SUB,
};

try {
  const { UserAttributes } = await cognitoidentityserviceprovider.adminGetUser(params).promise();
  ...
  ...
} catch (error) {
 return error;
}

问题是如何在 AppSync 解析器中使用 cognitoIdentityId 从 Cognito 用户池获取数据?或者还有其他选择吗?希望我不必为每个解析器创建单独的 lambda?

标签: amazon-web-servicesamazon-cognitoaws-appsync

解决方案


我假设您使用 AWS_IAM 作为 GraphQL API 的授权类型,并且您正在通过 Cognito Federated Identities 联合一个 cognito 用户池用户以获取用于调用 GraphQL API 的临时 AWS 凭证。

目前,联邦用户信息在 $context.identity 对象中不可用。解决方法是您发布的使用 lambda 检索它并通过使用管道解析器在解析器中进一步使用它的内容。

我是 AppSync 团队的一员,我们过去曾听说过此功能请求,因此我将代表您为您 +1。


推荐阅读