Flutter add client certificate to request using http.dart

Issue

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 acceps a http.client
something like this

import '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.

Solution

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'));
}

Answered By – Richard Heap

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *