2

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.

developerjamiu
  • 590
  • 8
  • 19

3 Answers3

2

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.

Sagar Acharya
  • 3,397
  • 4
  • 12
  • 34
  • This sounds amazing! Could you provide me an example here? https://stackoverflow.com/questions/63543452/firebase-auto-refresh-idtoken-keep-users-stay-logged-in?noredirect=1#comment112363704_63543452 – Marcel Dz Aug 23 '20 at 05:13
  • 1
    kindly elaborate it with little code example please. @sagar – saif aly Apr 29 '21 at 07:45
  • how do I update the token when the user leaves the app and comes back later and at that time both refresh token and token were expired? – reza47 May 04 '21 at 07:09
1

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);
});
saif aly
  • 545
  • 7
  • 8
0

How I solved this issue was:

  1. Save The access token, you may use secure storage or Shared Preferences, then call it:

final accessToken = await CustomSharedPreferences().getUserToken('userToken');

  1. Install the JwtDecoder Package from: https://pub.dev/packages/jwt_decoder/install

then use it:

      bool accessTokenHasExpired = JwtDecoder.isExpired(accessToken);
  1. 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');
      }
    
  2. 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;
    }
  }