AWS Cognito Migrate User Node.js Lambda函数已调用,但未按预期运行

fdbelqdn  于 2023-01-20  发布在  Node.js
关注(0)|答案(2)|浏览(103)

我创建了一个Migrate User Lambda函数,并将其连接到AWS Cognito Hosted UI。调用了Lambda,我在CloudWatch日志中看到了日志语句。除了托管UI的行为似乎与预期不符之外,一切似乎都正常。这几乎就像Lambda没有被调用一样。但我知道是因为我看到了日志语句,托管的UI总是显示“您输入的用户名或密码无效”,而我希望它将用户带到重置密码工作流。
我的节点功能为:

const https = require('https')

exports.handler = (event, context, callback) => {

    if ( event.triggerSource == "UserMigration_Authentication" ) {


        LoginUser(event.userName, event.request.password, function(user, message){
            
            console.log("Finished LoginUser call.");
            
            if ( user ) {
                console.log("Got a valid user with userId=" + user.userId);
                
                event.response.userAttributes = {
                    "userName" : user.userName,
                    "email": user.emailAddress,
                    "email_verified": "true",
                    "picture" : user.imageUrl,
                    "family_name" : user.lastName,
                    "given_name" : user.firstName,
                    "custom:userId" : user.userId
                };
                event.response.finalUserStatus = "RESET_REQUIRED";
                event.response.messageAction = "SUPPRESS";
                event.response.desiredDeliveryMediums = "EMAIL";
                
                console.log("Done: " + JSON.stringify(event));
                
                //callback(null,event);
                context.succeed(event);
            }
            else {
                console.log("User was not found. " + message );
                callback(message, event);
            }
        });
        
    }
    else if ( event.triggerSource == "UserMigration_ForgotPassword" ) {
        
        /*
         * Check to see if the user exists.  If so, then tell cognito
         * to proceed, given the email address we looked up.
         */
    	LookupUser(event.userName, function(user, message){
    	   
    	   if ( user ) {
    	       
                event.response.userAttributes = {
                    "email": user.emailAddress,
                    "email_verified": "true"  
                };
                event.response.messageAction = "SUPPRESS";

                console.log("Done: " + JSON.stringify(event));
                //callback(null,event);
                context.succeed(event);
    	   } 
    	   else {
    	       callback(message, event);
    	   }
    	   
    	});
	
    }
    else {
        callback("Bad triggerSource " + event.triggerSource);
    }
};





/*
 * Lookup a user
 */
function LookupUser(userName, UserCallback) {
    
    var pathUri = "/api/user?op=or&userName=" + encodeURIComponent(userName);	
    console.log("pathUri=" + pathUri);

    var headers = {
        "x-k-Id": process.env.kmpzPublicKey,
        "x-k-Sig": process.env.kmpzSecretKey
    };
    
    var options = {
        host: "www.mydomainhere.com",
        port: 443,
        path: pathUri,
        method: "GET",
        headers: headers
    };    

    var req = https.request(options, function(res) {  
        res.on('data', function(data) {
            
            var user = JSON.parse(data);
            console.log(user);
            
            if ( user.error ) {
                UserCallback(null, user.error.message);
            }
            else if ( user.userId ) {
                UserCallback(user, "OK");
            }
            else {
                UserCallback(null, "Unexpected response from userService.  Please contact Kompoz Customer Support.");
            }
        });
    });    
    
    req.on('error', function(e) {
        UserCallback(null, e.message);
    });    
  
    req.end();    
};



/*
 * Login a user
 */
function LoginUser(userName, userPassword, UserCallback) {
    
    var pathUri = "/api/auth/migrate?userName=" + encodeURIComponent(userName) + "&password=" + encodeURIComponent(userPassword);
    console.log("pathUri=" + pathUri);

    var headers = {
        "x-k-Id": process.env.kmpzPublicKey,
        "x-k-Sig": process.env.kmpzSecretKey
    };
    
    var options = {
        host: "www.mydomainhere.com",
        port: 443,
        path: pathUri,
        method: "POST",
        headers: headers
    };    

    var req = https.request(options, function(res) {  
        res.on('data', function(data) {
            
            var user = JSON.parse(data);
            console.log(user);
            
            if ( user.error ) {
                UserCallback(null, user.error.message);
            }
            else if ( user.userId ) {
                UserCallback(user, "OK");
            }
            else {
                UserCallback(null, "Unexpected response from userService.  Please contact Kompoz Customer Support.");
            }
        });
    });    
    
    req.on('error', function(e) {
        UserCallback(null, e.message);
    });    
  
    req.end();    
};

在CloudWatch日志中,我看到了响应:

{
    "version": "1",
    "triggerSource": "UserMigration_Authentication",
    "region": "us-east-1",
    "userPoolId": "us-east-1_******",
    "userName": "exampleUser",
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "2s12aui53t9a4n85orc3d3ul0u"
    },
    "request": {
        "password": "*******",
        "validationData": null,
        "userAttributes": null
    },
    "response": {
        "userAttributes": {
            "userName": "exampleUser",
            "email": "me@example.com",
            "email_verified": "true",
            "picture": "https://s3.amazonaws.com/example-s3/images/m1006-20140119-033844-p2.jpg",
            "family_name": "Smith",
            "given_name": "John",
            "custom:userId": 1006
        },
        "forceAliasCreation": null,
        "finalUserStatus": "RESET_REQUIRED",
        "messageAction": "SUPPRESS",
        "desiredDeliveryMediums": "EMAIL"
    }
}

我得到的是:

rekjcdws

rekjcdws1#

希望我能帮上忙。只是来这里说“我也是”。你收到HTTP/401错误了吗?我的lambda也在运行,但我无法通过错误消息。在cloudwatch中没有日志,在cloudtrail中没有提示。

HTML/401

Request URL: https://******.auth.us-west-2.amazoncognito.com/login?response_type=code&client_id=**************************&redirect_uri=https://local.******.com/auth/login
Request Method: GET
Status Code: 401 
Remote Address: 54.191.35.239:443
Referrer Policy: no-referrer-when-downgrade
cache-control: private
content-language: en-US
content-type: text/html;charset=UTF-8
date: Mon, 02 Sep 2019 04:45:17 GMT
expires: Thu, 01 Jan 1970 00:00:00 UTC
server: Server
set-cookie: cognito-fl="W10="; Version=1; Path=/; Secure; HttpOnly
status: 401
strict-transport-security: max-age=31536000 ; includeSubDomains
x-amz-cognito-request-id: 18e6f6e5-6c85-4280-81ac-b90428d66202
x-application-context: application:prod:8443
x-content-type-options: nosniff
x-frame-options: DENY
x-xss-protection: 1; mode=block
:authority: ******.auth.us-west-2.amazoncognito.com
:method: GET
:path: /login?response_type=code&client_id=************************&redirect_uri=https://local.******.com/auth/login
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
cookie: XSRF-TOKEN=b4c1c540-6eac-4309-bd81-1ce3cc54e259; cognito-fl="W3sidGFyZ2V0UmVxdWVzdFBhdGgiOiIvbG9naW4iLCJtYXAiOnsibG9naW5FcnJvck1lc3NhZ2UiOiJUaGUgdXNlcm5hbWUgb3IgcGFzc3dvcmQgeW91IGVudGVyZWQgaXMgaW52YWxpZCJ9fV0="
dnt: 1
pragma: no-cache
referer: https://******.auth.us-west-2.amazoncognito.com/login?response_type=code&client_id=***********************&redirect_uri=https://local.******.com/auth/login
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
response_type: code
client_id: ****************
redirect_uri: https://local.******.com/auth/login

λ响应

{
  "version": "1",
  "triggerSource": "UserMigration_Authentication",
  "region": "us-west-2",
  "userPoolId": "us-west-2_KIcLJftsn",
  "userName": "eflyerman@gmail.com",
  "callerContext": {
    "awsSdkVersion": "aws-sdk-unknown-unknown",
    "clientId": "**********************"
  },
  "request": {
    "password": "*********",
    "validationData": null,
    "userAttributes": null
  },
  "response": {
    "userAttributes": {
      "email_verified": true,
      "phone_number": "281******",
      "given_name": "E***e",
      "middle_name": "",
      "family_name": "S*****",
      "custom:role": "doctor|admin|",
      "custom:user_id": 528
    },
    "forceAliasCreation": null,
    "finalUserStatus": "CONFIRMED",
    "messageAction": "SUPPRESS",
    "desiredDeliveryMediums": "EMAIL"
  }
}
ao218c7q

ao218c7q2#

  1. awsdocs github repo包含migrate用户lambda的示例工作代码:注意,最后仅返回事件,在该工作示例中不使用上下文和回调。
    1.关于用户名/密码不正确的问题,一个可能的问题是,在设置用户池登录选项时,您同时选择了用户名和电子邮件。在这种情况下,用户池不允许为用户名设置电子邮件。对于此配置,仅当用户名为非电子邮件字符串时才允许迁移。

相关问题