AWS-JavaScript-使用经过身份验证的Cognito用户

时间:2019-05-23 18:01:59

标签: javascript amazon-web-services amazon-dynamodb amazon-cognito amazon-iam

尝试对具有特定用户权限的DynamoDB表执行CRUD操作(创建,读取,更新,删除)。

因此,我为表和与该策略关联的用户角色创建了IAM策略。 Ive还创建了我的用户和身份池。我相信剩下的就是我要做的实际编码。

所以我找到了亚马逊提供的这个CRUD SDK: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.03.html

SDK提供了对所需表执行CRUD操作的功能。这很棒。不过,根据我为表配置的权限,我不确定如何集成特定用户。

<html>
<head>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js">.
</script>

<script>
AWS.config.update({
  region: "us-west-2",
  endpoint: 'http://localhost:8000',
  // accessKeyId default can be used while using the downloadable version of DynamoDB. 
  // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
  accessKeyId: "fakeMyKeyId",
  // secretAccessKey default can be used while using the downloadable version of DynamoDB. 
  // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
  secretAccessKey: "fakeSecretAccessKey"
});

var docClient = new AWS.DynamoDB.DocumentClient();

function conditionalDelete() {
    var table = "Movies";
    var year = 2015;
    var title = "The Big New Movie";

    var params = {
        TableName:table,
        Key:{
            "year":year,
            "title":title
        },
        ConditionExpression:"info.rating <= :val",
        ExpressionAttributeValues: {
            ":val": 5.0
        }
    };

    docClient.delete(params, function(err, data) {
        if (err) {
            document.getElementById('textarea').innerHTML = "The conditional delete failed: " + "\n" + JSON.stringify(err, undefined, 2);
        } else {
            document.getElementById('textarea').innerHTML = "The conditional delete succeeded: " + "\n" + JSON.stringify(data, undefined, 2);
        }
    });
}

</script>
</head>

<body>
<input id="conditionalDelete" type="button" value="Conditional Delete" onclick="conditionalDelete();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px">
</textarea>

</body>
</html>

这是非常有用的代码。尽管在config.update中它们需要accessKeyId: "fakeMyKeyId"secretAccessKey: "fakeSecretAccessKey",但我如何用经过身份验证的Cognito用户替换它?

有人对此有任何想法或资源吗?我到处都看过。预先谢谢你!

1 个答案:

答案 0 :(得分:0)

对用户进行身份验证之后,可以使用GetCredentialsForIdentity方法来获取临时访问密钥,秘密密钥和会话令牌。您使用这三个凭证来访问AWS资源。因此,您将必须使用这些更新配置。请记住,这些密钥将在一个小时后失效。