如何从 lambda 函数内部访问 Cognito 用户池?

ata*_*ati 1 amazon-cognito aws-lambda aws-amplify

我在我的应用程序中使用 AWS Amplify 进行身份验证。我使用电子邮件地址作为 MFA 的用户名和电话号码。但是,我还需要电话号码是唯一的,因此我创建了这个预注册 lambda 触发器:

const aws = require('aws-sdk');

exports.handler = async (event, context, callback) => {
  const cognito = new aws.CognitoIdentityServiceProvider();

  const params = {
    AttributesToGet: [],
    Filter: `phone_number = "${event.request.userAttributes.phone_number}"`,
    Limit: 1,
    UserPoolId: event.userPoolId,
  };

  try {
    const result = await cognito.listUsers(params).promise();
    if(result.Users.length === 0) {
        callback(null, event);
    } else {
        const error = new Error("Phone number has already been used.");
        callback(error, event);
    }
  } catch (err) {
      console.log(err);
  }
};
Run Code Online (Sandbox Code Playgroud)

但是,该函数返回以下错误:

validatePhoneNumber-dev 无权在资源:xxx 上执行:cognito-idp:ListUsers

我该如何解决这个问题?

dan*_*nca 6

这意味着您的函数无权列出 Cognito 用户池上的用户

您需要在您的PreSignup-cloudformation-template.json文件中添加所需的权限:

在文件上,搜索lambdaexecutionpolicy, 然后PolicyDocument在其中搜索。在以下位置添加您所需的权限Statement

"Statement": [

    ...

    {
        "Sid": "Cognito",
        "Effect": "Allow",
        "Action": [
            "cognito-idp:ListUsers"
        ],
        "Resource": "arn:aws:cognito-idp:us-east-1:679504623344:userpool/xxxxx"
    }
Run Code Online (Sandbox Code Playgroud)

推动您的 Amplify 更改运行amplify push

现在应该可以了。