Skip to content

Instantly share code, notes, and snippets.

@kishandonga
Created August 9, 2023 13:34
Show Gist options
  • Save kishandonga/ed2ca8fcfdfb8e618a68d79250b53ca5 to your computer and use it in GitHub Desktop.
Save kishandonga/ed2ca8fcfdfb8e618a68d79250b53ca5 to your computer and use it in GitHub Desktop.
Using Dio lib interceptor handle refresh token case in the flutter
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class Api {
final Dio api = Dio();
String? accessToken;
final _storage = const FlutterSecureStorage();
Api() {
api.interceptors
.add(InterceptorsWrapper(onRequest: (options, handler) async {
options.headers['Authorization'] = 'Bearer $accessToken';
return handler.next(options);
}, onError: (DioError error, handler) async {
//Unauthorized error response
if ((error.response?.statusCode == 401) {
if (await _storage.containsKey(key: 'refreshToken')) {
if (await refreshToken()) {
return handler.resolve(await _retry(error.requestOptions));
}
}
}
return handler.next(error);
}));
}
Future<Response<dynamic>> _retry(RequestOptions requestOptions) async {
final options = Options(
method: requestOptions.method,
headers: requestOptions.headers,
);
return api.request<dynamic>(requestOptions.path,
data: requestOptions.data,
queryParameters: requestOptions.queryParameters,
options: options);
}
Future<bool> refreshToken() async {
final refreshToken = await _storage.read(key: 'refreshToken');
final response = await api
.post('/auth/refresh', data: {'refreshToken': refreshToken});
if (response.statusCode == 201) {
accessToken = response.data;
return true;
} else {
// refresh token is wrong
accessToken = null;
_storage.deleteAll();
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment