Java – Cognito User Pool : How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java SDK?

Cognito User Pool : How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java SDK?… here is a solution to the problem.

Cognito User Pool : How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java SDK?

I use AWS Cognito as my user management solution in a web application based on the Scala Play framework. I’m signing in with the following code.

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
}

The above code returns accessToken, expiresIn, tokenType, refreshToken, and idToken from the AWS Cognito server 。
According to the AWS documentation, when an accessToken expires to continue a user session, we can use refreshToken to get a new accessToken or idToken. However, there is no mention in the documentation about how to use refreshToken for this purpose. Any help with this would be appreciated. Thanks in advance.

Solution

I figured it out myself. Here is the working code

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
  }

Related Problems and Solutions