Skip to content

Instantly share code, notes, and snippets.

@erickvasilev
Created December 4, 2020 02:09
Show Gist options
  • Save erickvasilev/e2c026f6c317ca115f3796d175f38eac to your computer and use it in GitHub Desktop.
Save erickvasilev/e2c026f6c317ca115f3796d175f38eac to your computer and use it in GitHub Desktop.
Cognito Login Authentication via Lambda
//When stackoverflow can't help you...
const AWS = require('aws-sdk');
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var AuthenticationDetails = AmazonCognitoIdentity.AuthenticationDetails;
var CognitoUser = AmazonCognitoIdentity.CognitoUser;
exports.handler = (event, context, callback) => {
let user_name = 'youremail@email.com'
let pass_word = 'user password'
let user_pool_id = 'ap-southeast-x-xxxxx'
let user_pool_client_id = '3oro9erh'
let federated_identity_id = 'ap-southeast-1:46ffe098-cb9b-xxxxx'
var poolData = {
UserPoolId: user_pool_id,
ClientId: user_pool_client_id
};
var userPool = new CognitoUserPool(poolData);
AWS.config.region = 'ap-southeast-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: federated_identity,
});
var authenticationData = {
Username: user_name,
Password: pass_word
};
var authenticationDetails = new AuthenticationDetails(authenticationData);
var userData = {
Username: user_name,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
},
onFailure: function (err) {
console.log('Login error: ' + err);
}
});
}
@Tefferson
Copy link

This helped me.
I was missing the AWS.config.region and AWS.config.credentials.
However, I didn't add the AWS.config.credentials though.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment