5

I cannot find information on how to refresh access tokens using AWS' Amplify Android library.

In the documentation, and on some forums, it was suggested that it all happens automatically. But in my case, it does not.

In the app I use Amplify Auth for user authentication, also Amplify Storage and Amplify Predictions.

To query my database, I use the DynamoDBMapper from the AWS SDK for Android.

So far I have tried to force refresh the tokens in the following ways:

  1. auth.currentUser
  2. AWSMovileClient.getInstance().tokens
  3. AWSMobileClient.getInstance().currentUserState()
  4. Amplify.Auth.fetchAuthSession()

None of the first three were working. fetchAuthSession(...) is the technique I am using for now, but it is asynchronous and takes a moment to produce a result. I have to run it synchronously in my splash activity. Otherwise, if it is async and there is a request to the database right that depends on its results, the database call will cause a NotAuthorizedException.

Also, the refresh token can be set to like 10 years, so it is not a problem at the moment. The problem is that the new access token is not being created after the old one expires, and I cannot do any authenticated user action.

Is there a way to quickly check if tokens are valid -- and if not, refresh them?

Jameson
  • 6,400
  • 6
  • 32
  • 53
baltekg
  • 985
  • 9
  • 31
  • Does the following response solve your issue? https://stackoverflow.com/a/55614839/1721793 – sashimi Nov 19 '20 at 21:57
  • @kekec: this was @baltekg’s question. That link points to some JavaScript code. – Jameson Nov 19 '20 at 22:00
  • You are right. Here is a github issue asking for a similar functionality, and in this response they point how to achieve this in Android: https://github.com/aws-amplify/aws-sdk-android/issues/1204#issuecomment-569900713 – sashimi Nov 19 '20 at 22:18
  • @kekec i have already seen this issue and this technique doesn't work, getTokens() returns previous tokens and does not refresh them. Maybe sometimes it does, but from my testing, it was failing to do so. – baltekg Nov 19 '20 at 22:31
  • If you force a session refresh and ask for tokens? – sashimi Nov 20 '20 at 07:24
  • If i do what someone suggested in the answer in the link you provided – baltekg Nov 20 '20 at 10:06
  • ok, so that solved the issue? There was a follow-up issue addressing this same problem here: https://github.com/aws-amplify/aws-sdk-android/issues/2084 – sashimi Nov 20 '20 at 11:14
  • no, it doesn't work. It returns tokens but does not refresh them – baltekg Nov 20 '20 at 11:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224848/discussion-between-kekec-and-baltekg). – sashimi Nov 20 '20 at 12:55

1 Answers1

1

I took a look at the source code of "fetchauthsession", and changed the asynchronous mode to synchronous mode.

https://github.com/shichonghuotian/Amplify-token-sync

yong wei
  • 125
  • 1
  • 2