繁体   English   中英

如何从客户端强制刷新 cognito 令牌

[英]How can I force a cognito token refresh from the client

我正在使用 aws amplify,我知道令牌会在需要时自动刷新,并且这是在幕后完成的。

我需要做的是通过 Lambda 后端进程更改 cognito 用户池中用户的自定义属性。 我可以做到这一点,而且它正在发挥作用。 但是,web 客户端用户永远不会看到这个新的自定义属性,我认为他们看到它的唯一方法是刷新令牌,因为该值存储在 JWT 令牌中。

未记录,但您可以在用户上使用refreshSession方法。 您对 currentAuthenticatedUser 和 currentSession 的下一次调用将更新配置文件属性(和组)

User = Auth.currentAuthenticatedUser()
Session =  Auth.currentSession()

User.refreshSession(Session.refreshToken))

就像这里说的:

https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html

访问令牌和 ID 令牌有效期为 1 小时。 使用 Amplify,您可以使用Auth类中的currentSessioncurrentUserInfo获取有关会话的信息,以便能够检索有关令牌的信息。

以下是如何按需更新令牌(强制)

 import { Auth } from 'aws-amplify'; try { const cognitoUser = await Auth.currentAuthenticatedUser(); const currentSession = await Auth.currentSession(); cognitoUser.refreshSession(currentSession.refreshToken, (err, session) => { console.log('session', err, session); const { idToken, refreshToken, accessToken } = session; // do whatever you want to do now :) }); } catch (e) { console.log('Unable to refresh Token', e); }

截至 2021 年,正确的解决方案是调用await Auth.currentAuthenticatedUser({bypassCache: true})

@andreialecu 写下了正确答案。 获取 JWT 的完整代码:

static async amplifyRefresh() {
    try {
      const currentUser = await Auth.currentAuthenticatedUser({ bypassCache: true })      
      const currentSession = await Auth.currentSession()      
      const jwt = currentSession.getIdToken().getJwtToken()
      // do what you want
    } catch (error) {
      console.log("error refreshing token: ", error)
      throw error
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM