如何从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.