AWS : how to get cognito user attributes in Lambda/cloud logic

Lambda function(js)

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider();

function getUser(Username) {
    return new Promise((resolve, reject) => {
        cognito.adminGetUser({
            UserPoolId: process.env.COGNITO_USER_POOL_ID,
            Username: Username
        }, (err, data) => {
            if (err)
                reject(err.stack);
            else
                resolve(data.UserAttributes[2].Value);
        });
    });
}

async function getEmail(Username) {
  return await getUser(Username);
}

exports.handler = async (event) => {
    console.log(await getEmail('abcdef'));
    console.log(await getEmail('hijklmn'));
    console.log('done');
    return 'ok';
};
set Execution role with correct policy as below descripted.
set an environment 'COGNITO_USER_POOL_ID' with the user pool id.

Role policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "cognito-idp:AdminGetUser",
            "Resource": "your user pool arn"
        }
    ]
}
userpool

Eexcution Result

Response:
"ok"

Request ID:
"a327a22f-0363-11e9-a897-6f0106540a1d"

Function Logs:
START RequestId: a327a22f-0363-11e9-a897-6f0106540a1d Version: $LATEST
2018-12-19T07:56:49.880Z    a327a22f-0363-11e9-a897-6f0106540a1d    errong.leng
@gmail.com
2018-12-19T07:56:50.056Z    a327a22f-0363-11e9-a897-6f0106540a1d    errong.leng
@hotmail.com
2018-12-19T07:56:50.056Z    a327a22f-0363-11e9-a897-6f0106540a1d    done
END RequestId: a327a22f-0363-11e9-a897-6f0106540a1d
REPORT RequestId: a327a22f-0363-11e9-a897-6f0106540a1d  Duration: 1149.09 ms
 Billed Duration: 1200 ms    Memory Size: 128 MB Max Memory Used: 30 MB

Refers

AWS.CognitoIdentityServiceProvider.adminGetUser

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)