如何从Lambda函数内部访问Cognito Userpool? [英] How to access Cognito Userpool from inside a lambda function?

查看:62
本文介绍了如何从Lambda函数内部访问Cognito Userpool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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无权执行:资源:xxx上的cognito-idp:ListUsers

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

我该如何解决?

推荐答案

这意味着您的函数无权在Cognito UserPool上为listUsers

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

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

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

在文件上,搜索 lambdaexecutionpolicy ,然后在其中搜索 PolicyDocument .在声明下添加所需的权限:

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"
    }

运行 amplify push

现在应该可以正常工作了.

It should work now.

这篇关于如何从Lambda函数内部访问Cognito Userpool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆