Cognito 用户池:在 aws cognito java sdk 中访问令牌过期后如何使用刷新令牌获取新的访问令牌?

Cognito user pool: How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java sdk?

我在基于 scala play 框架的 Web 应用程序中使用 aws cognito 作为用户管理解决方案。我正在使用以下代码登录。

var mIdentityProvider: AWSCognitoIdentityProvider = getAmazonCognitoIdentityClient;

def sessionLogin(userName: String, password: String): AdminInitiateAuthResult = {
val authParams: java.util.Map[String, String] = new java.util.HashMap[String, String]()
    authParams.put("USERNAME", userName)
    authParams.put("PASSWORD", password)
    val authRequest = new AdminInitiateAuthRequest()
      .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
      .withUserPoolId("***")
      .withClientId("***")
      .withAuthParameters(authParams)
    val authResult = mIdentityProvider.adminInitiateAuth(authRequest)
    authResult
}

以上代码 returns accessToken、expiresIn、tokenType、refreshTokenidToken 来自 aws cognito 服务器。 根据 aws 文档,当 accessToken 过期以继续用户会话时,我们可以使用 refreshToken 获取新的 accessToken 或 idToken。但是在文档中没有提到如何为此目的使用 refreshToken。对此的任何帮助将不胜感激。提前致谢。

我自己想出来了。以下是工作代码

def refreshAccessToken(refreshToken: String): AuthenticationResultType = {
    val authParams: java.util.Map[String, String] = new java.util.HashMap[String, String]()
    authParams.put("REFRESH_TOKEN", refreshToken)
    val authRequest = new AdminInitiateAuthRequest()
      .withAuthFlow(AuthFlowType.REFRESH_TOKEN_AUTH)
      .withUserPoolId("***")
      .withClientId("***")
      .withAuthParameters(authParams)
    val authResult = mIdentityProvider.adminInitiateAuth(authRequest)
    val resultType: AuthenticationResultType = authResult.getAuthenticationResult
    resultType
  }

很高兴您找到问题的答案。为了帮助将来更多地成为其他人的资源,这里有一些有用的链接:

The AWS docs on token refresh

The Mobile SDK for iOS and the Mobile SDK for Android automatically refresh your ID and access tokens if there is a valid (non-expired) refresh token present, and the ID and access tokens have a minimum remaining validity of 5 minutes. If the refresh token is expired, your app user must reauthenticate by signing in again to your user pool.

另请注意,Amplify API includes logic to help with this. See this Git issue, and specifically this comment 即使在长时间 运行 操作期间也能保持令牌新鲜:

I ran into a situation where my Cognito JWT token was expiring on long-running S3 uploads (fails at the 1 hour mark). I couldn't find anything that gave a solution as to how you refresh the token in the middle of a request, so after hours of digging through the Amplify lib and AWS SDK, I finally figured out a solution. You do have to use the AWS SDK directly (sorry Amplify Storage)