Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

TokenExpired Error when Attempting to Refresh Access Token

Hello Fitbit Community,

I'm currently developing an application that interacts with Fitbit's API to fetch user data. I'm encountering an issue when trying to refresh the access token using the getRefreshToken() function. Specifically, I'm getting the following error:

Exception: TokenExpired

Here is the relevant code I'm using to refresh the token:

Future<String> getRefreshToken() async {
  try {
    final refreshToken = await SecureStorageUtils().read(key: 'refreshToken') ?? '';
    final response = await http.post(
      Uri.parse('https://api.fitbit.com/oauth2/token'),
      headers: {
        'Authorization': 'Basic $encodedCredentials',
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: {
        'grant_type': 'refresh_token',
        'refresh_token': refreshToken,
      },
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final newAccessToken = data['access_token'];
      final newRefreshToken = data['refresh_token'];

      await SecureStorageUtils().write(key: 'accessToken', value: newAccessToken);
      await SecureStorageUtils().write(key: 'refreshToken', value: newRefreshToken);
      await SettingServerLogic().authTokenChange();
      
      return newAccessToken;
    } else {
      throw Exception('Failed to refresh token: ${response.statusCode}');
    }
  } catch (e) {
    throw Exception('Failed to refresh token: $e');
  }
}

I am successfully retrieving the refresh token and making a request to the /oauth2/token endpointTokenExpired error.

Questions:

  1. What could be causing this TokenExpired error
  2. Is there a time limit on the refresh token's lifespan that I should be aware of?
  3. Could this issue be related to any recent changes in Fitbit's API policies or OAuth2 mechanisms?
  4. What is the best way to handle token expiration issues in a long-term, production environment?

Any help or guidance would be greatly appreciated!

Thanks in advance.

Best Answer
0 Votes
2 REPLIES 2

Hello,

I am currently using Flutter to retrieve Fitbit biometric data. When the access token expires, I follow the instructions provided at Fitbit API - Refresh Token to request a new token. However, I am encountering a TokenExpired error during the token refresh process, even though it has been less than two days since connecting Fitbit.

Future<String> getRefreshToken() async {
try {
final refreshToken = await SecureStorageUtils().read(key: 'refreshToken') ?? '';
final response = await http.post(
Uri.parse('https://api.fitbit.com/oauth2/token'),
headers: {
'Authorization': 'Basic $encodedCredentials',
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
'grant_type': 'refresh_token',
'refresh_token': refreshToken,
},
);

if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final newAccessToken = data['access_token'];
final newRefreshToken = data['refresh_token'];

await SecureStorageUtils().write(key: 'accessToken', value: newAccessToken);
await SecureStorageUtils().write(key: 'refreshToken', value: newRefreshToken);

await SettingServerLogic().authTokenChange();
return newAccessToken;
} else if (response.statusCode == 401) {
throw Exception('Failed to refresh token: ${response.statusCode}');
} else{
throw Exception('Failed to refresh token: ${response.statusCode}');
}
} catch (e) {
// error here!!
throw Exception('Failed to refresh token: $e');
}
}

Could you please explain why this error is occurring and how to handle it when it happens?

Thank you!

Best Answer
0 Votes

Hi @whwndud 

We have some information here on refreshing tokens and the time limits.  The main thing is the refresh tokens do not expire but can only be called once.

Gordon Crenshaw
Senior Technical Solutions Consultant
Fitbit Partner Engineering & Web API Support | Google
Best Answer
0 Votes