iOS Swift, AWS Cognito User Pool, Unable to Refresh Access Token

萝らか妹 提交于 2020-01-03 14:18:08

问题


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
}

回答1:


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       
        }
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/49142054/ios-swift-aws-cognito-user-pool-unable-to-refresh-access-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!