I use AWS Cognito and need to authorize a user through a lambda function. I have seen examples online and when I try to apply them, the Cognito authentication does not run and gets somehow skipped:
const AWS = require('aws-sdk');
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
global.fetch = require("node-fetch");
const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var AuthenticationDetails = AmazonCognitoIdentity.AuthenticationDetails;
var CognitoUser = AmazonCognitoIdentity.CognitoUser;
var USER_POOL_ID = 'my_pool_id';
var CLIENT_ID = 'my_client_id';
var idToken = '';
exports.handler = async (event, callback) => {
var email = event['username'];
var password = event['password'];
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
Username: email,
Password: password
});
const poolData = {
UserPoolId: USER_POOL_ID,
ClientId: CLIENT_ID
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: email,
Pool: userPool
}
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
var accessToken = result.getAccessToken().getJwtToken();
console.log(result);
console.log(accessToken);
idToken = result.idToken.jwtToken;
console.log(idToken);
callback(null, accessToken);
},
onFailure: (err) => {
console.log(err);
idToken = err;
callback(err);
},
});
console.log("cognitoUser after: ", cognitoUser);
};
I can see the last console.log printed in the logs, but lambda does not seem to wait for the request resolution of cognitoUser.authenticateUser, as none of the console.logs inside onSuccess or onFailure get printed.