我正在客户端浏览器上使用开发人员身份验证身份通过 Cognito 进行身份验证。当我的页面加载(或刷新)时,我希望我的应用程序记住身份,只要对象没有过期(我认为它持续大约一个小时)。但是,我不知道如何在无需再次通过开发人员身份验证的情况下从 Cognito 检索身份。
这是代码在页面加载时执行的操作:
var cognitoCredentials
$(document).ready(function() {
"use strict";
cognitoParams = {
IdentityPoolId: 'us-east-1:xxxxxxx'
};
cognitoCredentials = new AWS.CognitoIdentityCredentials(cognitoParams);
AWS.config.credentials = cognitoCredentials;
});
并且通过开发者认证登录后:
cognitoCredentials.params.IdentityId = output.identityId;
cognitoCredentials.params.Logins = {
'cognito-identity.amazonaws.com': output.token
};
cognitoCredentials.expired = true;
如果我已经登录,然后刷新页面,并尝试再次登录,我会收到一个错误,提示我在已经拥有一个身份的情况下尝试获取一个身份
错误:配置中缺少凭据(...)NotAuthorizedException:配置中缺少凭据
“禁止访问身份‘us-east-1:xxxxxxx’。”
但是,我不知道如何访问它。如何检索凭据,以便在刷新页面时检测到 Cognito 提供的先前身份?
最佳答案
在页面之间的sessionStorage
中至少保存accessKeyId、secretAccessKey、sessionToken
。您可以将它们加载到 AWS.config.credentials 中(当然是在加载 AWS SDK 之后)。这比等待 Cognito 响应要快得多。请记住,您必须使用来自提供商之一的 token 手动刷新它们,这仅在临时 token 过期(约 1 小时)之前有效。
var credKeys = [
'accessKeyId',
'secretAccessKey',
'sessionToken'
];
// After Cognito login
credKeys.forEach(function(key) {
sessionStorage.setItem(key, AWS.config.credentials[key]);
});
// After AWS SDK load
AWS.config.region = 'us-east-1'; // pick your region
credKeys.forEach(function(key) {
AWS.config.credentials[key] = sessionStorage.getItem(key);
});
// Now make your AWS calls to S3, DynamoDB, etc
关于javascript - 如何在浏览器中跨页面保留 Cognito 身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612530/