1 year ago

#375472

test-img

MElochukwu

How to start a countdown timer when app is initialized

A jwt is generated from the backend after user logs in. The Token only lasts for 60secs before expiry. I want the token to refresh in 10secs to expire. I want a timer that will countdown from Token time 10secs and then call the refreshToken method. I don't want to use Dio 401 interceptor due to security reasons. The jwt is needed to authorize the refresh token endpoint and generate a new jwt.

Example: When user logs in successfully, countdown timer should start from 60secs of jwt expiry time to 10secs before it expire and call the refresh Token method.

I couldn't come up with a better solution for the countdown timer logic, I tried using difference in time to check the differences in current time and Token expiry time but its not working.

This is the countdown timer method in homepage.

 @override
  void initState() {
    tokenTimer();
    super.initState();
  }

  RestartableTimer? timer;
  var counter = 0.obs;
  Future<void> tokenTimer() async {
    print("User Token Initialized");
    const secs = Duration(seconds: 1);
    final storage = GetStorage();
    var token = await storage.read("Token");
    var tokenExpiry = JwtDecoder.getExpirationDate(token);
    var currentTime = DateTime.now();
    var diff = tokenExpiry.difference(currentTime).inSeconds.obs;
    print(diff);
    timer = RestartableTimer(
      secs,
      (() {
        if (diff.value == 10) {
          print('REFRESHING TOKING');
          timer?.cancel();
          ApiService.refreshToken().whenComplete(() => timer?.reset());
        } else {
          diff.value--;
        }
      }),
    );
  }

Refresh Token method

  static Future<void> refreshToken() async {
    final token = await _storage.read('Token');
    _client.options.headers['Accept'] = 'application/json';
    _client.options.headers['Authorization'] = 'Bearer $token';
    final response = await _client.post('/refresh');
    if (response.statusCode == 200 || response.statusCode == 201) {
      final newAccessToken = response.data['Token'];
      print('New Token: $newAccessToken');
      _storage.write('Token', newAccessToken);
    } else if (response.statusCode == 401) {
      performLogout();
    }
  }

flutter

dart

jwt

dio

0 Answers

Your Answer

Accepted video resources