如何从 lambda 函数内部访问 Cognito Userpool?
How to access Cognito Userpool from inside a lambda function?
我在我的应用程序中使用 AWS Amplify 进行身份验证。我使用电子邮件地址作为用户名,并使用 phone 号码作为 MFA。但是,我还需要 phone 数字是唯一的,所以我创建了这个预注册 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);
}
};
但是,函数returns出现如下错误:
validatePhoneNumber-dev is not authorized to perform: cognito-idp:ListUsers on resource: xxx
我该如何解决?
这意味着您的函数无权在 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"
}
推送您的 Amplify 更改 运行 amplify push
现在应该可以了。
我在我的应用程序中使用 AWS Amplify 进行身份验证。我使用电子邮件地址作为用户名,并使用 phone 号码作为 MFA。但是,我还需要 phone 数字是唯一的,所以我创建了这个预注册 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);
}
};
但是,函数returns出现如下错误:
validatePhoneNumber-dev is not authorized to perform: cognito-idp:ListUsers on resource: xxx
我该如何解决?
这意味着您的函数无权在 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"
}
推送您的 Amplify 更改 运行 amplify push
现在应该可以了。