简体   繁体   中英

Refresh token in flutter

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:

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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM