Home > front end >  Flutter add client certificate to request using http.dart
Flutter add client certificate to request using http.dart

Time:01-18

I'm trying to load a client certificate to a a http.client from the http.dart package.

I'v seen multipule 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.crt');
SecurityContext context = SecurityContext.defaultContext;
context.useCertificateChainBytes(data.buffer.asUint8List());
client = HttpClient(context: context);

But i must use the http.dart packacge since i havem a function that acceps a http.client somthing 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.

CodePudding user response:

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'));
}
  •  Tags:  
  • Related