Fetching Cognito user's device attributes in lambda function

Viewed 409

I have created a lambda function which is getting triggered in Post-Confirmation of Cognito user pool authentication triggers. The idea is to put the user-id, phonenumber and user deviceKey(and all other device attributes) into my dynamodb user table, after the user is successfully authenticated. My users device attributes are getting captured successfully in Cognito and I can see them under each user.

I am able to get the userId and phone_number but I am unable to get the users device Attributes in the lambda function. Kindly help.

Below, is the code of the lambda function.

var aws = require('aws-sdk');
var ddb = new aws.DynamoDB({apiVersion: '2012-10-08'});


exports.handler = async (event, context) => {
    console.log(event);

    let date = new Date();

    const tableName = "user_table";
    const region = process.env.REGION;
    
    console.log("table=" + tableName + " -- region=" + region);

    aws.config.update({region: region});

    if (event.request.userAttributes.sub) {
        
        console.log("Event Requests", event.request);
        let ddbParams = {
            Item: {
                'id': {S: event.request.userAttributes.sub},
                'phone_number': {S: event.request.userAttributes.phone_number},
                'device_key' :    **//Need to fetch DeviceKey of the user. Solution required.**
            },
            TableName: tableName
        };

        try {
            await ddb.putItem(ddbParams).promise()
            console.log("Success");
        } catch (err) {
            console.log("Error", err);
        }

        console.log("Success: Everything executed correctly");
        context.done(null, event);

    } else {
        console.log("Error: Nothing was written to DDB or SQS");
        context.done(null, event);
    }
};
1 Answers

device_key (or any other device attribute) is not part of the Cognito standard attributes. In order to access it you need to prefix the name with custom::

// ...
device_key: {S: event.request.userAttributes['custom:device_key']},
// ...
Related