Using Interceptor in Dio for Flutter to Refresh Token
I have found a simple solution that looks like the following:
this.api = Dio();
this.api.interceptors.add(InterceptorsWrapper(
onError: (error) async {
if (error.response?.statusCode == 403 ||
error.response?.statusCode == 401) {
await refreshToken();
return _retry(error.request);
}
return error.response;
}));
Basically what is going on is it checks to see if the error is a 401
or 403
, which are common auth errors, and if so, it will refresh the token and retry the response. My implementation of refreshToken()
looks like the following, but this may vary based on your api:
Future<void> refreshToken() async {
final refreshToken = await this._storage.read(key: 'refreshToken');
final response =
await this.api.post('/users/refresh', data: {'token': refreshToken});
if (response.statusCode == 200) {
this.accessToken = response.data['accessToken'];
}
}
I use Flutter Sercure Storage to store the accessToken. My retry method looks like the following:
Future<Response<dynamic>> _retry(RequestOptions requestOptions) async {
final options = new Options(
method: requestOptions.method,
headers: requestOptions.headers,
);
return this.api.request<dynamic>(requestOptions.path,
data: requestOptions.data,
queryParameters: requestOptions.queryParameters,
options: options);
}
If you want to easily allows add the access_token
to the request I suggest adding the following function when you declare your dio router with the onError
callback:
onRequest: (options) async {
options.headers['Authorization'] = 'Bearer: $accessToken';
return options;
},
I solved it using interceptors in following way :-
Future<Dio> getApiClient() async {
token = await storage.read(key: USER_TOKEN);
_dio.interceptors.clear();
_dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
// Do something before request is sent
options.headers["Authorization"] = "Bearer " + token;
return options;
},onResponse:(Response response) {
// Do something with response data
return response; // continue
}, onError: (DioError error) async {
// Do something with response error
if (error.response?.statusCode == 403) {
_dio.interceptors.requestLock.lock();
_dio.interceptors.responseLock.lock();
RequestOptions options = error.response.request;
FirebaseUser user = await FirebaseAuth.instance.currentUser();
token = await user.getIdToken(refresh: true);
await writeAuthKey(token);
options.headers["Authorization"] = "Bearer " + token;
_dio.interceptors.requestLock.unlock();
_dio.interceptors.responseLock.unlock();
return _dio.request(options.path,options: options);
} else {
return error;
}
}));
_dio.options.baseUrl = baseUrl;
return _dio;
}
Dio 4.0.0 Support
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (request, handler) {
if (token != null && token != '')
request.headers['Authorization'] = 'Bearer $token';
return handler.next(request);
},
onError: (e, handler) async {
if (e.response?.statusCode == 401) {
try {
await dio
.post(
"https://refresh.api",
data: jsonEncode(
{"refresh_token": refreshtoken}))
.then((value) async {
if (value?.statusCode == 201) {
//get new tokens ...
print("access token" + token);
print("refresh token" + refreshtoken);
//set bearer
e.requestOptions.headers["Authorization"] =
"Bearer " + token;
//create request with new access token
final opts = new Options(
method: e.requestOptions.method,
headers: e.requestOptions.headers);
final cloneReq = await dio.request(e.requestOptions.path,
options: opts,
data: e.requestOptions.data,
queryParameters: e.requestOptions.queryParameters);
return handler.resolve(cloneReq);
}
return e;
});
return dio;
} catch (e, st) {
}
}
},
),
);