Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is a code for an auth interceptor for Dio, which uses a header to avoid retrying indefinitely to refresh the token.
/// This interceptor is simplified because is doesn't contemplate
/// a refresh token, which you should take care of.
/// I haven't tested this code, but I believe it should work.
/// If you have some feedback, please leave a comment and I'll review it :) Thanks.
class AuthInterceptor extends InterceptorsWrapper {
final Dio loggedDio;
final Dio tokenDio;
final SomeLocalStorage localStorage;
AuthInterceptor({this.loggedDio, this.tokenDio});
@override
Future onRequest(RequestOptions options) async {
/// access token obtained via API after user logged in and saved into
/// some local storage
final accessToken = localStorage.getAccessToken();
options.headers['Authorization'] = accessToken;
return options;
}
@override
Future onError(DioError error) async {
if (e.response?.statusCode == 401) {
//This retries the request if the token was updated later on
RequestOptions options = error.response.request;
if (options.headers['Authorization'] != localStorage.getAccessToken()) {
return loggedDio.request(options.path, options: options);
} else {
_lockDio();
if (options.headers['Retry-Count'] == 1) {
_unlockDio();
// Here you might want to logout the user
return error;
}
return tokenDio.get("/token").then((response) {
localStorage.setAccessToken(response.data['data']['token']);
}).whenComplete(() {
_unlockDio();
}).then((e) {
options.headers['Retry-Count'] = 1;
return loggedDio.request(options.path, options: options);
}).catchError((e) {
// Here you might want to logout the user
return e;
});
}
} else {
return error;
}
}
void _retryRequest() {
}
void _lockDio() {
loggedDio.lock();
loggedDio.interceptors.responseLock.lock();
loggedDio.interceptors.errorLock.lock();
}
void _unlockDio() {
loggedDio.unlock();
loggedDio.interceptors.responseLock.unlock();
loggedDio.interceptors.errorLock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment