How to access Cognito Userpool from inside a lambda function?

别等时光非礼了梦想. 提交于 2021-01-29 13:47:56

问题


I'm using AWS Amplify for authentication in my app. I'm using email address as username and phone number for MFA. But, I also need the phone numbers to be unique, so I created this pre-signup lambda trigger:

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);
  }
};

But, the function returns the following error:

validatePhoneNumber-dev is not authorized to perform: cognito-idp:ListUsers on resource: xxx

How can I resolve that?


回答1:


This means your function has no permission to listUsers on the Cognito UserPool

On your PreSignup-cloudformation-template.json file you need to add the required permission:

On the file, search for the lambdaexecutionpolicy, and then PolicyDocument inside it. Add your required permission under Statement:

"Statement": [

    ...

    {
        "Sid": "Cognito",
        "Effect": "Allow",
        "Action": [
            "cognito-idp:ListUsers"
        ],
        "Resource": "arn:aws:cognito-idp:us-east-1:679504623344:userpool/xxxxx"
    }

Push your Amplify changes running amplify push

It should work now.



来源:https://stackoverflow.com/questions/62014773/how-to-access-cognito-userpool-from-inside-a-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!