I'm working on a finance project (Flutter) where the auth token gotten from the back-end expires frequently.
How can I keep the token from expiring as long as the user is using the app.
I'm working on a finance project (Flutter) where the auth token gotten from the back-end expires frequently.
How can I keep the token from expiring as long as the user is using the app.
What I suggest is you can handle the things in simple manner like when fetching the data if the token expires you get a 401 unAuthorized Exception where you can ask for a new token(refresh Token) and then make the fetch request again. Let me know if it worked for you.
Use oauth_dio: ^0.2.3 https://pub.dev/packages/oauth_dio
OAuthToken token = oauth.requestToken(
  RefreshTokenGrant(
    refreshToken: '<YOUR REFRESH TOKEN>'
  )
).then((token) {
    print(token.accessToken);
});
How I solved this issue was:
final accessToken = await CustomSharedPreferences().getUserToken('userToken');
then use it:
      bool accessTokenHasExpired = JwtDecoder.isExpired(accessToken);
Using Dio with interceptors:
 if (accessTokenHasExpired) {
 print('Inside Access Token has Expired');
 dio.interceptors.requestLock.lock();
 dio.interceptors.responseLock.lock();
 dio.interceptors.errorLock.lock();
 _refreshed = await _regenerateAccessToken();
 dio.interceptors.requestLock.unlock();
 dio.interceptors.responseLock.unlock();
 dio.interceptors.errorLock.unlock();
 print('Outside Access Token');
  }
the _regenerateAccessToken method:
 _regenerateAccessToken() async {
    try{
      var refreshToken = await CustomSharedPreferences().getRefreshToken('refreshToken');
      print("This is the refresh token: $refreshToken");
      var body = {
        "refresh_token": refreshToken,
      };
      
var dio = Dio();
      Response response = await dio.post(ApiConstant.REFRESH_TOKEN, data: body,options: Options(
        receiveTimeout: 5000,
        headers:{
          "Accept": "application/json",
          "Content-Type": "application/json;charset=UTF-8",
        },
        validateStatus: (status){
          return status! <= 500;
        },
      ),
    );
      if (response.statusCode == 200 || response.statusCode == 201 ) {
      RefreshTokenModel refreshToken = RefreshTokenModel.fromJson(response.data);
      await CustomSharedPreferences().setUserToken(refreshToken.idToken);
      
      var checkTime = JwtDecoder.getRemainingTime(refreshToken.idToken);
      CustomSharedPreferences().setRefreshToken(refreshToken.refreshToken);
      return true;
      }
      else {
        print("Refresh Token Server Responded Back with: ${response.statusCode}");
        return false;
      }
    }
    on DioError{
      return false;
    }
    catch (e) {
      return false;
    }
  }