0

I'd like to attach an IoT policy to the Cognito identities given to the federated users of my app. I'm tryng to do this with a Lambda function in the Post confirmation trigger of my user pool. Here's my function so far:

const AWS = require('aws-sdk');
const iot = new AWS.Iot();

exports.handler = async function(event, context) {

    const policyName = 'arn:aws:iam::XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const target = context.identity.cognitoIdentityId;
    await iot.attachPolicy({ target, policyName }).promise();

    const response = {
        statusCode: 200,
        body: JSON.stringify('Policy attached.'),
    };
    return response;
};

When this function runs I get an error:

"cannot read property 'cognitoidentityid' of undefined"

Similar error if I define principal as

const principal = context.cognito_identity_id; //error: "Missing required key 'target' in params"

According to the Iot docs, "The context object in your Lambda function contains a value for context.cognito_identity_id when you call the function with AWS credentials that you obtain through Amazon Cognito Identity pools." Can anyone tell me how to do that?

I should add that I would like to attach this policy for both desktop and mobile users.The Lambda docs imply that the identity property of the context object is provided for mobile apps only. If that is true then is there a different way to attach the IoT policy to all Cognito identites, mobile and desktop alike?

Thanks

David U
  • 943
  • 1
  • 8
  • 22

1 Answers1

1

To sum up, You will not be able to get identity id in Cognito's post confirmation trigger.

To overcome it, Client can invoke separate Lambda function (once user is confirmed) and in that Lambda you can attach policy, because here you will get identity id.

Other alternative which I don't prefer is client themselves attach a policy after user confirmation.

Attach Policy API - https://docs.aws.amazon.com/iot/latest/apireference/API_AttachPolicy.html

Tejaskumar
  • 754
  • 8
  • 24