来自 Lambda 的 AWS Cognito adminCreateUser,使用 Amplify CLI 创建

Posted

技术标签:

【中文标题】来自 Lambda 的 AWS Cognito adminCreateUser,使用 Amplify CLI 创建【英文标题】:AWS Cognito adminCreateUser from Lambda, created with Amplify CLI 【发布时间】:2021-02-24 13:19:44 【问题描述】:

我使用 Amplify CLI 创建了一个 Lambda 函数,执行 Lambda 函数时执行没有错误,但未创建 Cognito 用户。

我在这里错过了什么?

我已经检查了 CloudWatch Logs,但也没有我可以获取的错误。

我一直在关注这个文档:https://docs.aws.amazon.com/AWSjavascriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminCreateUser-property

/* Amplify Params - DO NOT EDIT
    AUTH_XXXXXXXXXXXXXXXXXXXX_USERPOOLID
    ENV
    REGION
Amplify Params - DO NOT EDIT */

const AWS = require('aws-sdk');
AWS.config.update( region: process.env.AWS_REGION,accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY );

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider( apiVersion: '2016-04-18' );

//console.log(process.env);

exports.handler = async (event) => 
    let retailerid = event.pathParameters.retailerid;

    let params = 
        UserPoolId: process.env.AUTH_XXXXXXXXXXXXXXXXXXXX_USERPOOLID, /* required */
        Username: 'testtest', /* required */
        ClientMetadata: 
        ,
        DesiredDeliveryMediums: [
            'EMAIL'
        ],
        ForceAliasCreation: false,
        MessageAction: 'SUPPRESS',
        TemporaryPassword: 'mynuw000000000TTS',
        UserAttributes: [
            
                Name: 'custom:app_role', /* required */
                Value: 'retail'
            ,
            
                Name: 'email_verified', /* required */
                Value: 'true'
            ,
            
                Name: 'email', /* required */
                Value: 'usersname@someemail.co.za'
            ,
            
                Name: 'phone_number', /* required */
                Value: '27833260000'
            ,
            /* more items */
        ],
        ValidationData: [

            /* more items */
        ]
    ;
    await cognitoidentityserviceprovider.adminCreateUser(params, function (err, data) 
        if (err) console.log(err, err.stack); // an error occurred
        else console.log('SUCCESS', data);           // successful response
    );

    // TODO implement
    const response = 
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: 
            "Access-Control-Allow-Origin": "*"
        ,
        body: JSON.stringify(retailerid),
    ;
    return response;
;

【问题讨论】:

【参考方案1】:

测试活动


 "request": 
"userAttributes": 
  "custom:name": "Ajay",
  "email": "ajay@gmail.com",
  "custom:role": "Admin"

,
"response": 
 

Lambda 函数

var AWS = require('aws-sdk');

var resp200ok =  statusCode: 200, headers: 'Content-Type': 'application/json', body:  ;

var cognitoidentityserviceprovider = new 
       AWS.CognitoIdentityServiceProvider(apiVersion: '2016-04-18');


exports.handler = function(event, context, callback)
const attributes = event.request.userAttributes;  // read user attributes from event

console.log('User Role : ',attributes['custom:role'])

 var params = 
    UserPoolId:'*********',
    Username: attributes.email,
    //TemporaryPassword: 'Password!1',
    DesiredDeliveryMediums: ["EMAIL"],
    UserAttributes: [
       
            Name: "email",
            Value: attributes.email
      ,
      
            Name: 'email_verified', /* required */
            Value: 'true'
      ,
      
            Name: 'custom:name', /* required */
            Value: attributes['custom:name']
      ,
      
            Name: 'custom:role', /* required */
            Value: attributes['custom:role']
      ,
    ],
;

cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) 
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log('SUCCESS', data);           // successful response
);

;

【讨论】:

【参考方案2】:

我不确定 await 是否有效。这个怎么样。

var createUserPromise = cognitoidentityserviceprovider.adminCreateUser(params).promise();

createUserPromise.then(results => 
    // TODO implement
    const response = 
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: 
            "Access-Control-Allow-Origin": "*"
        ,
        body: JSON.stringify(retailerid),
    ;
    return response;
    )
   .catch(err => 
          console.log("Error: ", err);
          return "err"
        );

【讨论】:

【参考方案3】:
await cognitoidentityserviceprovider.adminCreateUser(params).promise()
  .then((data) => 
    console.log('SUCCESS', data);  
  )
  .catch((error) => 
    console.log('ERROR', error);  
  );

这会起作用

【讨论】:

以上是关于来自 Lambda 的 AWS Cognito adminCreateUser,使用 Amplify CLI 创建的主要内容,如果未能解决你的问题,请参考以下文章

在 DotNet 中创建 AWS Cognito PreSignup Lambda

当 AWS AppSync 使用 Cognito 时如何验证 Lambda 生成的突变

我是不是需要在 Lambda 和 API 网关中验证 AWS Cognito 令牌?

带有 ADFS 的 AWS Cognito:颁发者与 providerName 不匹配

AWS Lambda、API 网关和 Cognito:如何在 lambda 函数中获取身份对象?

如何在 API 网关上的 cognito 授权方保护的 lambda 函数中获取 AWS Cognito 用户数据