I try to move a request with certificate from an old system made with NodeJS to a new system using .NET 8.0.
Running the .NET code, however, I always get the following error:
The SSL connection could not be established
Here is my NodeJS code:
const Q = require('q');
return Q.Promise((resolve, reject) => {
const options = {
method: 'POST',
url: ConfigPayment.kmobile.url + '/targetUrl',
headers: {
'cache-control': 'no-cache',
'content-type': 'text/xml;charset=UTF-8',
'SoapAction': '',
},
agentOptions: {
ca: [
fs.readFileSync('file1.pem'),
fs.readFileSync('file2.pem'),
fs.readFileSync('file3.crt'),
fs.readFileSync('file4.crt'),
fs.readFileSync('file5.crt'),
fs.readFileSync('file6.crt')
]
},
strictSSL: true,
body: xml
}
This is my new .NET 8.0 code:
var _trustedCertificates = new X509Certificate2Collection();
var filePathList = new string[]
{
Path.Combine(this.ProjectRootPath, "file1.pem"),
Path.Combine(this.ProjectRootPath, "file2.pem"),
Path.Combine(this.ProjectRootPath, "file3.crt"),
Path.Combine(this.ProjectRootPath, "file4.crt"),
Path.Combine(this.ProjectRootPath, "file5.crt"),
Path.Combine(this.ProjectRootPath, "file6.crt")
};
foreach (var path in filePathList)
{
if (File.Exists(path))
{
logger.LogDebug($"Files exists {path}");
var cert = new X509Certificate2(path);
_trustedCertificates.Add(cert);
}
}
var handler = new HttpClientHandler()
{
SslProtocols = SslProtocols.Tls12,
ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
{
logger.LogDebug("ServerCertificateCustomValidationCallback called. Errors: {Errors}", errors);
if (errors == SslPolicyErrors.None)
return true;
using var chain2 = new X509Chain();
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
foreach (var c in _trustedCertificates)
{
chain2.ChainPolicy.ExtraStore.Add(c);
}
var serverCert = cert as X509Certificate2 ?? new X509Certificate2(cert);
var isValid = chain2.Build(serverCert);
foreach (var status in chain2.ChainStatus)
{
logger.LogDebug("Chain error: {Status} - {Info}", status.Status, status.StatusInformation);
}
return isValid;
}
};
this.httpClient = new HttpClient(handler);
this.httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
this.httpClient.DefaultRequestHeaders.Add("SoapAction", "");
this.httpClient.BaseAddress = new Uri("https://targetUrl.com/");
Does anyone know what I am doing wrong?