Skip to content

Instantly share code, notes, and snippets.

@namphho
Created May 2, 2021 06:43
Show Gist options
  • Save namphho/0628143cd366f57dca9992be1aff539d to your computer and use it in GitHub Desktop.
Save namphho/0628143cd366f57dca9992be1aff539d to your computer and use it in GitHub Desktop.
dio interceptor
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