furaiev/amazon-cognito-identity-dart-2

How to use refresh token to keep session valid?

aidandavis opened this issue · 9 comments

Hi,

I have been using this package with great success for months now.

Every month or so, if I don't do a new login, the user is kicked out with the error that the 'refresh token has expired'.

How to I keep the refresh token up to date?

Error is: CognitoClientException{statusCode: 400, code: NotAuthorizedException, name: NotAuthorizedException, message: Refresh Token has expired}

Hi,
Token refreshment is a full app's responsibility.
You can try to refresh it onCatch NotAuthorizedException or checking the token expiration time.

@furaiev is there a method to get a new token? How do I actually do the refresh?

  • you can cache token _cognitoUser.cacheTokens();
  • you can check token validity smth like:
  bool checkTokenValidity(String token) {
      if (DateTime.now().add(Duration(minutes: 5)).isBefore(tokenExpiration(token));) {
        return true;
      }
      return false;
  }

  DateTime tokenExpiration(String token) {
    final parts = token.split('.');

    if (parts.length != 3) {
      throw InvalidTokenException();
    }

    final payloadMap = json.decode(_decodeBase64(parts[1]));

    if (payloadMap is! Map<String, dynamic>) {
      throw InvalidPayloadException();
    }

    return DateTime.fromMillisecondsSinceEpoch(payloadMap['exp'] * 1000);
  }

  String _decodeBase64(String str) {
    var output = str.replaceAll('-', '+').replaceAll('_', '/');

    switch (output.length % 4) {
      case 0:
        break;
      case 2:
        output += '==';
        break;
      case 3:
        output += '=';
        break;
      default:
        throw InvalidBase64Exception();
    }

    return utf8.decode(base64Url.decode(output));
  }
  • for refreshing session you can use cognitoUser.refreshSession(session.refreshToken);

thank you! if I have any issues I will raise it as a new issue.

I think this example should be in the documentation somewhere if it isn't already.

very useful, I think there should be a paragraph with this code on the readme

I agree, wasn't something i was aware of until my users started seeing that error once every month or so.

Hi guys I found an issue regarding the refresh token.
When you call session.refreshToken make sure you save cognitoUser.cacheTokens(); after authenticateUser.
That will help you to make sure you wouldn't get this error like me before Local storage is missing an ID Token, Please authenticate.

Hope my reply will help.

If we use the federated login, how do we get new accessTokens? Federated login doesn't create a cognitoUser for me to authenticate with.