Created
January 5, 2021 11:40
-
-
Save douglasiacovelli/8fe98ec4a98e72bef5da1189a19fb3b9 to your computer and use it in GitHub Desktop.
This is a code for an auth interceptor for Dio, which uses a header to avoid retrying indefinitely to refresh the token.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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
Not yet! I'll be checking this this week and return if I have any news :)