1

I want to print data from the api so I need to refresh the bearer token every time it expires so how can I refresh token everytime when it expires using my code below,. Your help will be appreciated. I have a function where I get my token called getToken() and I am using the token in response there and using it in my signInData() to get data from the api, now I want to update that token when it expires, please check my code below

getToken function I get null on r.data, please tell where I did wrong

Future<void> getToken([data]) async {
    
    String basicAuth =
        'Basic ${base64Encode(utf8.encode('$username:$password'))}';
    print(basicAuth);

    Response r = await _dio.post('$_baseUrl/services/token',
        // headers: <String, String>{'authorization': basicAuth});
        options: Options(headers: {"authorization": basicAuth}));

    print("status code");
    print(r.statusCode);
    print(data);
    print("data:" + r.data);
  }

signInData function

  Future<void> signInData([data]) async {
    try {
      Response response = await _dio.post('$_baseUrl/api/gateway',
          data: {
            {
              "ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
              "PlatformId": "ios",
              "ClientUserId": "AhmedOmar",
              "VinNumber": VINumber
            }
          },
          options: Options(headers: {
            "Content-Type": "application/json",
            "Authorization":
                "Bearer 2HDqoyEa1hkH9FXcUM04M2o010UWAKTgqJnCEVjIwLFlE7pTqhui2flMnW71pnl77ns4iBrE6KQ1dRXd2x9r4ImXX7",
          }));
      print(response.data);
      print(response.statusCode);
    } catch (e) {
      print(e);
    }
  }
SaDev
  • 145
  • 1
  • 11

1 Answers1

3

Hey if statusCode ==401` then first call you refresh token api and using the updated token call signInData, For more details about Shared Preference Read Here

I will suggest you to read how to use Retrofit with Dio package

Sample code is below -

Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";

    try {
      Response response = await _dio.post('$_baseUrl/api/gateway',
          data: {
            {
              "ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
              "PlatformId": "ios",
              "ClientUserId": "AhmedOmar",
              "VinNumber": VINumber
            }
          },
          options: Options(headers: {
            "Content-Type": "application/json",
            "Authorization":
                "Bearer $token",
          }));
      print(response.data);
      print(response.statusCode);
 if(response.statusCode == 401){
   // call your refresh token api here and save it in shared preference
    await getToken();
    signInData(data); 
}
    } catch (e) {
      print(e);
    }
  }

here is refresh token api method

    Future<void> getToken() async {
    
    String basicAuth =
        'Basic ${base64Encode(utf8.encode('$username:$password'))}';
    print(basicAuth);

    Response r = await _dio.post('$_baseUrl/services/token',
        // headers: <String, String>{'authorization': basicAuth});
        options: Options(headers: {"authorization": basicAuth}));

    print("status code");
    print(r.statusCode);
    print(data);
    print("data:" + r.data);
   // Save your token here 
   final prefs = await SharedPreferences.getInstance();
   await prefs.setString("token", r.data["Token"]);
  }
Harish Sharma
  • 1,189
  • 1
  • 8
  • 19
  • Hi @Harish Sharma, I am still new to this, tell me how to call refresh token api using my code please. – SaDev Jun 21 '22 at 06:24
  • Hey i have updated my answer check it – Harish Sharma Jun 21 '22 at 06:28
  • 1
    Thanks man, so one last thing, can you please help me create my refreshtokenApi() and as I have read, I saw storing tokens using sharedpreference is not secured, so they advised using flutter_secure_storage, may you please my brother. – SaDev Jun 21 '22 at 06:41
  • Yes, you are absolutely right flutter_secure_storage is more secure then sharedpreference use can use any of them as per your choice and because i don't know what is payload of your refresh token api and what is response so i can't create refreshtokenApi() same as per your requirements but i will update a sample code in answer – Harish Sharma Jun 21 '22 at 06:51
  • Please check, I have updated my question. – SaDev Jun 21 '22 at 06:54
  • Did you check your /services/token api working fine or not in postman, because i am not seeing any error in your getToken method – Harish Sharma Jun 21 '22 at 07:12
  • I have applied your code and it gives error when I call signInData(), – SaDev Jun 21 '22 at 07:14
  • It gives the following error: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences) – SaDev Jun 21 '22 at 07:14
  • this error is not related to my code this is related to configuration for more details check this question - https://stackoverflow.com/questions/66001793/flutter-missingpluginexceptionno-implementation-found-for-method-getall-on-chan or https://stackoverflow.com/questions/50687801/flutter-unhandled-exception-missingpluginexceptionno-implementation-found-for – Harish Sharma Jun 21 '22 at 07:17
  • Thanks man, yes on the getToken(), it is working on postman – SaDev Jun 21 '22 at 07:25
  • is your problem solved now? – Harish Sharma Jun 21 '22 at 07:27
  • Sorry man, got it fixed, it is working now, the getToken() – SaDev Jun 21 '22 at 07:27
  • Okey, enjoy coding – Harish Sharma Jun 21 '22 at 07:28
  • So does your refreshtoken api refreshes that token that I got from the response.data from the getToken()? – SaDev Jun 21 '22 at 07:29
  • i have update my answer according to your code, you need to call getToken() instead of refreshTokenApi() now – Harish Sharma Jun 21 '22 at 07:30
  • I already did mate – SaDev Jun 21 '22 at 08:07