Search code examples
flutterdio

Flutter Bearer Token Refresh


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);
    }
  }

Solution

  • 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"]);
      }