Reputation: 167
I would like to know if it is possible to have a global HTTP interceptor to attach token in header for all requests in Flutter? I've searched a lot and couldn't find any information as where and how to set it up as globally. Thanks a lot!
Upvotes: 9
Views: 16941
Reputation: 4394
This answer is an extension of Felipe Medeiros's answer that I could not edit. It is not actually a global way to attach a token to every requests, but should be considered nonetheless to create interceptors/middleware.
BaseClient is part of the native http package. You can extend BaseClient and override send(BaseRequest request)
:
class BearerTokenMiddleware extends BaseClient {
final Future<String> Function() getBearerToken;
BearerTokenMiddleware({required this.getBearerToken});
@override
Future<StreamedResponse> send(BaseRequest request) async {
request.headers.addAll({
'Authorization': 'Bearer ${await getBearerToken()}',
});
return request.send();
}
}
When one of your classes needs the http client, inject the BaseClient
abstraction to the constructor. Exemple:
class HTTPTodoGateway implements TodoGateway {
final BaseClient httpClient;
HTTPTodoGateway ({required this.httpClient});
getTodoById(string todoId) {
httpClient.get(Uri.parse('https://mytodos/$todoId'));
}
}
You can then create a new instance of HTTPTodoGateway
with an instance of BearerTokenMiddleware
that will wrap your requests with an authentication bearer header.
Upvotes: 0
Reputation: 151
You can extend BaseClient and override send(BaseRequest request)
:
class CustomClient extends BaseClient {
static Map<String, String> _getHeaders() {
return {
'Authentication': 'c7fabcDefG04075ec6ce0',
};
}
@override
Future<StreamedResponse> send(BaseRequest request) async {
request.headers.addAll(_getHeaders());
return request.send();
}
}
In the above example the 'Authentication': 'c7fabcDefG04075ec6ce0'
is hardcoded and not encrypted which you should never do.
Upvotes: 7
Reputation: 914
Flutter provides http_interceptor.dart package.
Sample
class LoggingInterceptor implements InterceptorContract {
@override
Future<RequestData> interceptRequest({RequestData data}) async {
print(data);
return data;
}
@override
Future<ResponseData> interceptResponse({ResponseData data}) async {
print(data);
return data;
}
}
Upvotes: 1
Reputation: 5172
Using dio package u can do that :
Dio dio = Dio(BaseOptions(
connectTimeout: 30000,
baseUrl: 'your api',
responseType: ResponseType.json,
contentType: ContentType.json.toString(),
))
..interceptors.addAll(
[
InterceptorsWrapper(onRequest: (RequestOptions requestOptions) {
dio.interceptors.requestLock.lock();
String token = ShareP.sharedPreferences.getString('token');
if (token != null) {
dio.options.headers[HttpHeaders.authorizationHeader] =
'Bearer ' + token;
}
dio.interceptors.requestLock.unlock();
return requestOptions;
}),
// other interceptor
],
);
Upvotes: 1