Reputation: 31
I have a Dio client with an interceptor attached, but when I try to add some headers, they don't appear in logs. his is my code
Dio dio(KeyStore keyStore) {
final Dio dio = Dio(BaseOptions(
contentType: 'application/json',
connectTimeout: 5000,
sendTimeout: 5000,
));
final Dio tokenDio = Dio();
tokenDio.interceptors.add(LogInterceptor(responseBody: true));
dio.interceptors.add(LogInterceptor(responseBody: true));
dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) async {
final accessToken = await keyStore.readAccessToken();
final branchId = keyStore.readBranchId();
dio.lock();
options.headers[HttpHeaders.authorizationHeader] = 'Bearer: $accessToken';
options.headers['x-tenant'] = branchId;
handler.next(options);
dio.unlock();
}));
return dio;
}
Request headers...
I/flutter ( 8872): *** Request ***
I/flutter ( 8872): uri: https://api.someapi.com/users/058c026a-2dce-47e7-9fe1-61dec507265f
I/flutter ( 8872): method: GET
I/flutter ( 8872): responseType: ResponseType.json
I/flutter ( 8872): followRedirects: true
I/flutter ( 8872): connectTimeout: 5000
I/flutter ( 8872): sendTimeout: 5000
I/flutter ( 8872): receiveTimeout: 0
I/flutter ( 8872): receiveDataWhenStatusError: true
I/flutter ( 8872): extra: {}
I/flutter ( 8872): headers:
I/flutter ( 8872):
Upvotes: 3
Views: 2766
Reputation: 3435
Dio interceptors are run in order. Since your auth interceptor is added after the log interceptor, LogInterceptor
is called first, before the auth interceptor has a chance to add headers. The interceptor code looks fine to me, so I suspect that the authorization headers are correctly sent to the remote server.
To make your logs reflect the headers added by the auth interceptor, make sure LogInterceptor
is the last element of the list dio.interceptors
.
Upvotes: 3
Reputation: 1547
You don't necessarily need to use an interceptor. You can update the default options like this:
dio.options.headers = {
HttpHeaders.authorizationHeader: 'Bearer: $accessToken',
'x-tenant': branchId
}
Then subsequent requests will use these values by default.
Upvotes: 0