getMTLSHttpClient function
Create an HttpClient with mTLS configuration.
Implementation
HttpClient? getMTLSHttpClient() {
final mtlsConfig = getMTLSConfig();
final caCerts = getCACertificates();
if (mtlsConfig == null && caCerts == null) return null;
// In Dart, SecurityContext is the equivalent of HTTPS agent options
final context = SecurityContext(withTrustedRoots: true);
if (mtlsConfig?.cert != null) {
try {
context.useCertificateChainBytes(utf8.encode(mtlsConfig!.cert!));
} catch (e) {
stderr.writeln('mTLS: Failed to set client certificate: $e');
}
}
if (mtlsConfig?.key != null) {
try {
context.usePrivateKeyBytes(
utf8.encode(mtlsConfig!.key!),
password: mtlsConfig.passphrase,
);
} catch (e) {
stderr.writeln('mTLS: Failed to set client key: $e');
}
}
if (caCerts != null) {
for (final cert in caCerts) {
try {
context.setTrustedCertificatesBytes(utf8.encode(cert));
} catch (e) {
stderr.writeln('mTLS: Failed to add CA certificate: $e');
}
}
}
return HttpClient(context: context);
}