javascript - 如何刷新 AWS JS SDK v3 中的凭证?
问题描述
NotAuthorizedException
我正在尝试将我的 V2 应用程序迁移到 V3 SDK,但在以下调用引发with后,我似乎无法弄清楚如何刷新凭据"Invalid login token. Token expired: 1615301743 >= 1615108625"
。
credentials = await cognitoIdentity.send(
new GetIdCommand({
Storage: config,
IdentityPoolId: config.get("IdentityPoolId"),
Logins: {
[`cognito-idp.${awsRegion}.amazonaws.com/${upid}`]: idToken,
},
}),
);
在 V2 中,有一个refresh()
在Credentials
对象上调用的方法,我可以调用它并通过这样做来刷新凭据。如何用新的 API 做同样的事情?
解决方案
我在以下链接中找到了以下代码示例(检查用例 4): https ://www.npmjs.com/package/amazon-cognito-identity-js
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error(error);
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log('Successfully logged!');
}
});
在 AWS Lambda 中实施时,它对我有用。希望这是您正在寻找的。
问候,
编辑:
我刚刚测试了以下代码,它适用于我的 react-js 应用程序:
return new Promise((resolve, reject) =>
cognitoUser.authenticateUser(authenticationDetails, {
// If the provided credentials are correct.
onSuccess: function(result) {
var accessToken = result.getAccessToken().getJwtToken();
//POTENTIAL: Region needs to be set if not already set previously elsewhere.
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId, // Your identity pool id here.
Logins: {
// Change the key below according to the specific Region your User Pool is in.
`cognito-idp.${awsRegion}.amazonaws.com/${upid}`: result
.getIdToken()
.getJwtToken(),
},
});
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error(error);
} else {
resolve(AWS.config.credentials)
}
});
},
// If the provided credentials are incorrect.
onFailure: function(err) {
console.log(err);
reject(
err.message || JSON.stringify(err)
);
},
})
);
推荐阅读
- c - typedef 用不同类型重新定义('struct word' vs 'struct word')};
- ios - 如何模拟扫描 QR UI 测试用例而不在 Swift iOS 中打开相机视图?
- featuretools - featuretools:手动推导dfs生成的特征?
- plot - Octave:如何使用仪器控制包绘制未知长度的串行数据?
- reactjs - Auth0 isAuthenticated 始终为假
- android - Android - 从自定义列表视图中删除一个项目并在长按时更新它
- c++ - WIN32对话框抛出异常
- javascript - Dropzone JS:在添加的文件上集成 Cropper JS。如何调用 done 函数来完成“transformFile”参数?
- assemblyscript - 带有空格的 AssemblyScript 导出名称
- javascript - 单击时不执行简单 console.log 的 Jquery 事件处理程序