问题
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