让我先从我想要实现的内容的整体描述开始 . 我正在使用Lambda,Cognito(联合身份),API网关等构建无服务器API . 我正在使用aws_iam作为API Gateway中的授权人 . 在某些 endpoints ,我需要访问例如用户电子邮件或用户名或其他任何内容,以便我可以在响应中将其发回(也是未提出请求的用户的数据) . 我想我正在寻找对身份池的某种“管理员”访问权限,以便我可以根据cognitoIdentityId检索数据 .
现在,就我而言,这些数据存储在Cognito的数据集中 . 问题是,如何从Lambda函数(node.js)访问这些数据?这是一个很好的方法吗?我应该使用其他东西而不是数据集吗?某处有一个有效的例子吗?
如有必要,我很乐意提供更多细节 .
谢谢
EDIT #1:
这是我的lambda函数的代码:
module.exports.getDataSet = (event, context, callback) => {
console.log("event: " + JSON.stringify(event));
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID
});
try {
AWS.config.credentials.get(function() {
var client = new AWS.CognitoSync();
var params = {
DatasetName: 'userinfo',
IdentityId: event.requestContext.identity.cognitoIdentityId,
IdentityPoolId: IDENTITY_POOL_ID
};
client.listRecords(params, function (err, data) {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(data);
}
});
});
} catch (ex) {
callback(ex);
}
};
这是我在 err
中调用 listRecords
时得到的:
{ "message": "Missing credentials in config", "code": "CredentialsError", "time": "2017-05-26T08:42:39.298Z", "requestId": "46712a9b-41ef-11e7-9e3c-074afafb3349", "statusCode": 400, "retryable": false, "retryDelay": 21.688148977111666, "originalError": { "message": "Could not load credentials from CognitoIdentityCredentials", "code": "CredentialsError", "time": "2017-05-26T08:42:39.298Z", "requestId": "46712a9b-41ef-11e7-9e3c-074afafb3349", "statusCode": 400, "retryable": false, "retryDelay": 21.688148977111666, "originalError": { "message": "Unauthenticated access is not supported for this identity pool.", "code": "NotAuthorizedException", "time": "2017-05-26T08:42:39.298Z", "requestId": "46712a9b-41ef-11e7-9e3c-074afafb3349", "statusCode": 400, "retryable": false, "retryDelay": 21.688148977111666 } } }
EDIT #2:
通过删除解决
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID
});
从代码中将 AmazonCognitoReadOnly
策略添加到调用lambda的角色 .
1 回答
首先,您需要Lambda函数知道调用者的Cognito身份 . API网关中的request context包含Cognito id,您可以将其放入发送到Lambda函数的有效负载中,或使用Lambda代理集成并自动包含它 .
在Lambda中拥有Cognito id后,您可以使用它从Cognito Sync中检索关联的数据集 . 您可以使用像AmazonCognitoReadOnly这样的IAM策略来授予Lambda函数在Cognito Sync上调用ListRecords API的权限(这使您可以访问数据集) .