Home > Net >  How to refresh jwt token when it expires flutter
How to refresh jwt token when it expires flutter

Time:06-18

I am trying to send a http request for refresh token automatically when token expires while the user is using app. I want to refresh token in background without disturbing the application.

CodePudding user response:

There are 2 ways to do this.

1.You can store access token expiry in local storage and when the access token expires then you can call an api for new access token.

  1. Make common methods for all the rest api calls and then when token expires there is some specific response you can apply check on that and call again an api for new access token.

    Future getCall({required String url}) async {
    final Response response = await get(
      Uri.parse(url),
      headers: {
       'token': await LocalStorage.getAccessToken(),
      });
    
     if (response.statusCode == 200) {
       final data = json.decode(response.body);
       return data;
     } 
     else if (response.statusCode == 400 && response.body == "Token Expired") 
     {
       await _getAcessTokenFromRefresh();
       await getCall(url: url);
      } 
     }
    

CodePudding user response:

In addition to @Shubham choudhary answer, you can setup a Request Retrying Logic to all the HTTP requests from the app, so that any failed request gets another chance to be executed again with extra logic around it, this extra logic may be your Refresh Token Logic (The API call to refresh the token and store the new one).

If you are using http package, refer to its add-on package called http_interceptor which provides you with a mechanism for Retrying Requests with an example in the documentation for your case of token expiration:

Sometimes you need to retry a request due to different circumstances, an expired token is a really good example. Here's how you could potentially implement an expired token retry policy with http_interceptor.

class ExpiredTokenRetryPolicy extends RetryPolicy {
  @override
  Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
    if (response.statusCode == 401) {
      // Perform your token refresh here.

      return true;
    }

    return false;
  }
}

If you are using dio then you can do the same logic with also an add-on package called dio_smart_retry, you can refer to its documentation in pub.dev to learn more about it.

  • Related