getToken method

Returns a previously required token, if any, or requires a new one.

If a token already exists but is expired, a new token is generated through the refresh_token grant.

Implementation

Future<AccessTokenResponse?> getToken() async {
  _validateAuthorizationParams();

  var tknResp = await getTokenFromStorage();

  if (tknResp != null) {
    if (tknResp.refreshNeeded()) {
      //The access token is expired
      if (tknResp.hasRefreshToken()) {
        tknResp = await refreshToken(tknResp);
      } else {
        //No refresh token, fetch a new token
        tknResp = await fetchToken();
      }
    }
  } else {
    tknResp = await fetchToken();
  }

  if (!tknResp.isValid()) {
    throw Exception(
        'Provider error ${tknResp.httpStatusCode}: ${tknResp.error}: ${tknResp.errorDescription}');
  }

  if (!tknResp.isBearer()) {
    throw Exception('Only Bearer tokens are currently supported');
  }

  return tknResp;
}