Reputation: 157
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.
Upvotes: 0
Views: 989
Reputation: 2993
Here are couple of options
Remove async
from exports.handler = async (event, callback)
.
Keep async and wrap authenticateUser
as Promise
and use await
const res = await new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
var accessToken = result.getAccessToken().getJwtToken();
console.log(result);
console.log(accessToken);
idToken = result.idToken.jwtToken;
console.log(idToken);
resolve(accessToken);
},
onFailure: (err) => {
console.log(err);
idToken = err;
reject(err);
},
});
}
Note: Code has not been tested.
Upvotes: 2