felangel / fresh

🍋 A token refresh library for Dart.
https://github.com/felangel/fresh
360 stars 57 forks source link

Request headers bug #72

Closed Abilay99 closed 4 months ago

Abilay99 commented 1 year ago

I can't refresh token because of i use accessToken for API refreshToken for refreshing token but _httpClient interceptors using Fresh. There are changed headers Authorization only for refreshToken. How to solve this problem?

felangel commented 1 year ago

Can you share some sample code or a reproduction sample? I'm not sure I fully understand the problem you're facing, thanks!

Abilay99 commented 1 year ago
class TranslateApiClient {
  TranslateApiClient({Dio? httpClient})
      : _httpClient = (httpClient ?? Dio())
    ..options.baseUrl = baseUrl
    ..interceptors.add(_fresh)
    ..interceptors.add(
      LogInterceptor(),
    )
    ..options.followRedirects=false
    ..options.validateStatus=((status) => status != null && status <= 505);

  final Dio _httpClient;

  static final _fresh = Fresh.oAuth2(
    tokenHeader: (token){
      if (token.accessToken == '') {
        return {};
      }
      return {
        'Authorization': '${token.tokenType} ${token.accessToken}',
      };
    },
    tokenStorage: CacheTokenMemory(),
    refreshToken: (token, client) async {
      client.options.headers.addAll(
        {
          'Authorization': '${token?.tokenType} ${token?.refreshToken}',
        },
      );
      try {
        final response = await client.post<dynamic>('/auth/refresh',);

        if(response.statusCode != 201 || response.statusCode != 200){
          throw RevokeTokenException();
        }

        final data = response.data as Map<String, dynamic>;
        final accessToken = data['access_token'].toString();
        final refreshToken = data['refresh_token'].toString();

        return OAuth2Token(
          accessToken: accessToken,
          refreshToken: refreshToken,
        );
      } on DioError catch(err){
        print(err.message);
      }
      return const OAuth2Token(
        accessToken: '',
      );
    },
  );
}
felangel commented 4 months ago

Closing for now since this issue is quite old. If this is still an issue with the latest version of the package let me know and I'm happy to take a closer look, thanks!