在我们的用例中,我们需要使用以下方式对用户进行身份验证
AuthFlow: REFRESH_TOKEN
基本上使用this method
有没有办法使用 amazon-cognito-identity-js 包来做到这一点? 我们将idToken、accessToken和refreshToken存储在localstorage中,我们还可以存储用户的用户名(sub)
我们的第一个想法是使用“userSession.refreshSession”,但问题是,要使用此方法,我们需要调用 UserPool.getCurrentUser() ,在我们的例子中,它返回“null”,因为 token 是在没有使用的情况下获取的sdk,并且我们在本地存储中还没有 CognitoIdentityServiceProvider.****.LastAuthUser 和该库依赖的其他 key 。
有没有办法初始化 CognitoUser 对象并使用用户的 token 和电子邮件/用户名对其调用身份验证?
最佳答案
如果登录没有 amazon-cognito-identity-js
并且不存储用户名,
UserPool.getCurrentUser()
返回 null
在 localStorage 中,键为 CognitoIdentityServiceProvider.${this.clientId}.LastAuthUser
(请参阅 getCurrentUser )
如果您要手动管理 token ,您需要执行以下操作:
const poolData = {
UserPoolId: '...', // Your user pool id here
ClientId: '...', // Your client id here
};
const username = '' // TODO: get user name from a storage
const refreshToken = '' // TODO: get token from a storage
const userPool = new CognitoUserPool(poolData);
const userData = {
Username: username,
Pool: userPool,
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.refreshSession(
new CognitoRefreshToken({
RefreshToken: refreshToken
}),
(error, session) => {
/* TODO: save new tokens to your local storage */
})
其中 session 是 CognitoUserSession 的实例
注意:如果您使用后端进行登录/注册,我建议您使用后端来刷新 token
关于javascript - AWS Cognito js : init and authenticate CognitoUser using existing Refresh/Access/id Tokens and username,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76474711/