Created
May 2, 2021 06:43
-
-
Save namphho/0628143cd366f57dca9992be1aff539d to your computer and use it in GitHub Desktop.
dio interceptor
This file contains 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
import 'package:app/data/storage/auth/auth_shared_references.dart'; | |
import 'package:dio/dio.dart'; | |
import 'package:kiwi/kiwi.dart'; | |
class AuthenticationInterceptor extends Interceptor{ | |
AuthSharedPreferences _authSharedPreferences = KiwiContainer().resolve<AuthSharedPreferences>(); | |
@override | |
Future onRequest(RequestOptions options) async { | |
// #1 get access token from storage | |
String token = await _authSharedPreferences.getAccessToken(); | |
//#2: edit header | |
options.headers.addAll({'Authorization': 'Bearer $token'}); | |
return super.onRequest(options); | |
} | |
@override | |
Future onError(DioError err) { | |
return super.onError(err); | |
} | |
@override | |
Future onResponse(Response response) { | |
return super.onResponse(response); | |
} | |
} | |
class RestClient{ | |
final Dio restClient = Dio(); | |
void setUp() { | |
//#3: add authentication interceptor | |
restClient.interceptors.addAll([AuthenticationInterceptor()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment