5

Looked at similar SO questions which didn't help me resolve the issue.

I am using AWS Cognito User Pools in our iOS App. We are able to successfully create and login the user. However after about an Hr the access token is not available, I understand from AWS Cognito documentation that the iOS SDK automatically refreshes (also mentioned here) and obtains the token when it is not available, however I don't see this behaviour. The below code shows how I am trying to obtain the access token.

Using iOS SDK AWSCognitoIdentityProvider 2.6.7

Please advice how I can resolve the issue.

let mySession = self.pool.currentUser()?.getSession()

guard let accessToken = mySession?.result?.accessToken?.tokenString as? String else {
  print("Unable to obtain access token")
  self.handleSignOut() // Signing out the user since there is no access token       
  return
}
SpaceX
  • 2,814
  • 2
  • 42
  • 68

2 Answers2

3

getSession() returns an AWSTask.

You have to access the tokenString in the callback.

The following code works for me:

self.pool.currentUser()?.getSession().continueWith { task in

    if task.error == nil {
        let session = task.result! as AWSCognitoIdentityUserSession
        guard let accessToken = session.idToken?.tokenString; as? String else {
           print("Unable to obtain access token")
           self.handleSignOut() // Signing out the user since there is no access token       
        }
    }
}
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Kevin Sun
  • 33
  • 4
0

You shouldn't cache session or tokenString. If you do, the AWS library has no way of executing code to know when it expires or refresh when it does. From what I have read (and what we have done with both the Android and iOS Cognito SDKs) the correct way is to call getSession() each time you want a token. Under the hood, the AWS library will either return you a cached session immediately or go do the work to refresh the session (aka get a new token).

If you're not calling getSession() from the main thread, you could just block on the AWSTask returned from getSession(). Otherwise, this can be not-trivial to implement because you and AWSTask that will be completed later.

You can check the session's expirationTime property, and use a token from it if it isn't expired. But you're still going to handle the case where the session is expired and the AWS library needs to do a async work to refresh.

kbyrd
  • 3,321
  • 27
  • 41