Quantcast
Channel: Active questions tagged https - Stack Overflow
Viewing all articles
Browse latest Browse all 1818

Flutter: How to refresh the token within the allowable time of the access token when it is still valid?

$
0
0

I'm new to Flutter and using the http package for network calls.My goal is to refresh the token and retry the request if the access token has expired. I’ve seen the Dio package mentioned, but it seems complicated to me, so I’d prefer to stick with http.Problem:I want to:Check if the access token has expired before making an API call.If expired, call the refresh token API to get a new token.Retry the original request with the new token.This res to loginThis res to refresh-tokenThis my app flutter:

This login function to POST accesstoken

 static Future<bool> loginUser(String email, String password) async {    try {      var reqBody = {"email": email, "password": password};      var response = await http.post(        Uri.parse(login),        headers: {"Content-Type": "application/json"},        body: jsonEncode(reqBody),      );      var jsonResponse = jsonDecode(response.body);      if (jsonResponse['status']) {        SharedPreferences prefs = await SharedPreferences.getInstance();        prefs.setString('token', jsonResponse['token']);        prefs.setString('refreshToken', jsonResponse['refreshToken']);        return true;      } else {        return false;      }    } catch (error) {      throw Exception('Failed to login user: $error');    }  }
static DateTime? lastApiCallTime;  static Future<void> checkAndRefreshToken() async {    if (lastApiCallTime != null &&        DateTime.now().difference(lastApiCallTime!).inMinutes < 3) {      return;    }    lastApiCallTime = DateTime.now();    await refreshAccessToken();  }
static Future<bool> refreshAccessToken() async {    SharedPreferences prefs = await SharedPreferences.getInstance();    String? refreshToken = prefs.getString('refreshToken');    if (refreshToken == null) {      throw Exception('No refresh token found');    }    try {      var response = await http.post(        Uri.parse(refreshTokenUrl),        headers: {"Content-Type": "application/json"},        body: jsonEncode({'refreshToken': refreshToken}),      );      if (response.statusCode == 200) {        var jsonResponse = jsonDecode(response.body);        prefs.setString('token', jsonResponse['token']);        print('New token: ${jsonResponse['token']}');        return true;      } else {        return false;      }    } catch (error) {      print('Failed to refresh token: $error');      return false;    }  }

I’m not sure how to properly retry the original request after refreshing the token.

How can I:Detect when the token has expired (e.g., response 401 or similar).Automatically refresh the token and retry the request with the new token.


Viewing all articles
Browse latest Browse all 1818

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>