Flutter add client certificate to request using http.dart
1,905
Don't use the http.Client()
constructor. Instead, construct an IOClient
(which is a subclass of Client
as can be used instead). Pass in your HttpClient
.
import 'dart:io';
import 'package:http/io_client.dart';
void main() async {
final context = SecurityContext.defaultContext;
// modify context as needed
final httpClient = HttpClient(context: context);
final client = IOClient(httpClient);
await client.get(Uri.parse('https://somewhere.io'));
}
Author by
Yonatan
Updated on January 03, 2023Comments
-
Yonatan over 1 year
I'm trying to load a client certificate to a http.client from the http.dart package.
I'v seen multiple answers on how to do it using the HttpClient class, like this answer: Flutter add self signed certificate from asset folder, which basicaly suggests to do the following code
ByteData data = await rootBundle.load('assets/raw/certificate.pfx'); SecurityContext context = SecurityContext.defaultContext; context.useCertificateChainBytes(data.buffer.asUint8List()); context.usePrivateKeyBytes(data.buffer.asUint8List()); client = HttpClient(context: context);
But I must use the http.dart package since i have a function that accepts a
http.client
something like thisimport 'package:http/http.dart' as http; var httpClient = http.Client(); // i'd like to configure this httpClient to use a specific client certificate var client = MyClient(httpClient); .... MyClient (http.Client? httpClient) { -- some constructor logic -- }
Is there any way to configure a
http.client
to use a client certificate?Thanks.
-
G H Prakash over 2 yearsRemove as http and var http = Client();
-
-
Yonatan over 2 yearsThank you for the answer, but i'm getting an error
Unsupported operation: default SecurityContext getter
running a flutter web app, it seems like dart:io is a support for non-web applications, any workaround? -
Yonatan over 2 yearswhat i ended up doing was, adding a condition to check the platform (kIsWeb) and return
http.Client()
in a case of web -
Richard Heap over 2 yearsIndeed, but I assumed that you'd be using mobile rather than web, as that might be a security hole to load a client cert from assets on web.
-
NothingBox over 1 year@Yonatan, how do you check the platform and return dynamic client?
-
Pranav Sawant over 1 yearHow did you get around this error ? Unsupported operation: default SecurityContext getter running a flutter web app ? Did it ever work in web ?
-
Yonatan over 1 year@NothingBox there are several ways to detect the platform, here is an example How do you detect the host platform from Dart code
-
Yonatan over 1 year@PranavSawant was not able to get it to work in web