如何获得用户的cognito IdentityId

时间:2017-02-20 13:14:43

标签: aws-lambda amazon-cognito

我有一个AWS Lambda函数,它作为触发器附加到" Post确认"事件

我需要获取已创建的用户的IdentityId,我该怎么做?

这是我的代码:

'use strict';
var AWS = require('aws-sdk');
var region = 'eu-west-1'
var sqs = new AWS.SQS({region : region});
var s3 = new AWS.S3({region : region});
var util = require('util');
let awsAccountId = 'xx';
let queueName = 'xx';

// this function saves public user data to a bucket where clients can access it.

let putObjectToS3 = (bucket, key, data, contentType, callback) => {
        let params = {
            Bucket : bucket,
            Key : key,
            Body : data,
            CacheControl: "max-age=864000",
            ContentType: contentType
        }
        s3.putObject(params, callback);
}

let sendSQSMessage = (dataStr, callback) => {
  let queueURL = 'https://sqs.' + region + '.amazonaws.com/' + awsAccountId + '/' + queueName;
  let params = {
    MessageBody: dataStr,
    QueueUrl: queueURL
  };
  sqs.sendMessage(params, callback);
}

exports.handler = (event, context, callback) => {
    console.log('event', event)

    let S3key = 'publicuserdata/' + event.request.userAttributes.sub + '.json';
    let publicUserData = {};
    publicUserData['IdentityId'] = context.identity.cognitoIdentityId; //doesn't seem to work
    publicUserData['region'] = event.region;
    publicUserData['userName'] = event.userName;
    publicUserData['userPoolId'] = event.userPoolId;

    let finishLambdaCallback = (err, result) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('success', result)
            context.done(null, event)
        }
    };

    let funcOne = (callback) => {
        let data = util.inspect(context)
        //let data = JSON.stringify(context, null, 2)

        putObjectToS3(  'files.example.org', 
                        S3key, 
                        data, 
                        'application/json',
                        callback);
    }

    let funcTwo = (callback) => {
        let data = util.inspect(context)
        //let data = JSON.stringify(context, null, 2)
        sendSQSMessage(data, callback);
    }

    funcOne(() => {funcTwo(finishLambdaCallback)})

};

1 个答案:

答案 0 :(得分:0)

听起来可能会对身份池和用户池的交互方式感到困惑。

只有在使用Cognito联合身份证明提供的凭据调用Lambda时,才会使用身份ID填充context.identity.cognitoIdentityId。当它只是来自Cognito用户池的lambda调用时,情况并非如此。

Cognito用户池和Cognito联合身份是两个独立的服务,将用户池视为联合身份的另一个身份提供者。这意味着当您的用户池中的用户是,您必须实际使用为该用户出售的令牌以在您的身份池中创建身份时,不会自动创建身份ID。因此,如果要在该用户的标识池中创建标识,请使用id标记调用GetId。有关详细信息,请参阅this docs page