简体   繁体   中英

C# HttpClient with X509Certificate2 - WebException: The request was aborted: Could not create SSL/TLS secure channel

I'm working on implementing a payment service called Swish and testing it using this guide (Guide is in English even though filename is Swedish).

https://www.getswish.se/content/uploads/2015/06/Guide-Testverktyg_20151210.zip

As you can see the test project contains two certificates, .p12 and .pem file. I have tried to authenticate the request with both.

However even though trying solutions I found to this problem I still get the error.

As suggested here I implemented logging and this is the result. Pastebin link due to character limitation. I do not see anything pointing to StatusCode=401 in the logs so I don't think it is HTTP 401 Unauthorized .

public class PaymentRequest
{
    [JsonProperty("payeePaymentReference")]
    public string PayeePaymentReference { get; set; }

    [JsonProperty("callbackUrl")]
    public string CallbackUrl { get; set; }

    [JsonProperty("payerAlias")]
    public string PayerAlias { get; set; }

    [JsonProperty("payeeAlias")]
    public string PayeeAlias { get; set; }

    [JsonProperty("amount")]
    public string Amount { get; set; }

    [JsonProperty("currency")]
    public string Currency { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new SwishService();

        var paymentRequest = new PaymentRequest();
        paymentRequest.PayeePaymentReference = "0123456789";
        paymentRequest.CallbackUrl = "https://example.com/api/swishcb/paymentrequests";
        paymentRequest.PayerAlias = "4671234768";
        paymentRequest.PayeeAlias = "1231181189";
        paymentRequest.Amount = "100";
        paymentRequest.Currency = "SEK";
        paymentRequest.Message = "Kingston USB Flash Drive 8 GB";

        service.SendPaymentRequest(paymentRequest);
    }
}

public class SwishService
{
    private HttpClient client;
    public SwishService()
    {
        var baseAddress = new Uri("https://mss.swicpc.bankgirot.se");

        var certHandler = new WebRequestHandler();
        certHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
        certHandler.UseDefaultCredentials = false;

        //Same result with Swish Merchant Test Certificate 1231181189.p12 file
        var certPath = $"C:\\Users\\<Path>\\Testcertifikat\\Test Swish Root CA v1 Test.pem";

        var certificate = new X509Certificate2(certPath, "swish");
        certHandler.ClientCertificates.Add(certificate);

        client = new HttpClient(new LoggingHandler(certHandler));
        client.BaseAddress = baseAddress;
        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    }

    public void SendPaymentRequest(PaymentRequest paymentRequest)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                               | SecurityProtocolType.Tls11
                                               | SecurityProtocolType.Tls12
                                               | SecurityProtocolType.Ssl3;

        //Code throws exception before this callback is called
        ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };

        var content = new StringContent(JsonConvert.SerializeObject(paymentRequest), Encoding.UTF8, "application/json");

        var response = client.PostAsync("/swish-cpcapi/api/v1/paymentrequests/", content).Result;

        var resultStream = response.Content.ReadAsStreamAsync().Result;
        var result = string.Empty;

        using (var streamReader = new StreamReader(resultStream))
        {
            result = streamReader.ReadToEnd();
        }
    }

}

Update:

Using Postman in Chrome I could send a request after first importing the certificate in Chrome and then through mmc in the store Trusted Root Certification Authorities . I have not managed to find a solution in code yet. PS: The hosting for the application requires that the certificate is loaded from file and not fetched from a certificate store.

在此处输入图片说明

Update 2:

System diagnostics log with stack trace:

https://pastebin.com/qMz6X6yJ

Found an SSL test performed on the server:

https://www.ssllabs.com/ssltest/analyze.html?d=mss.swicpc.bankgirot.se

From here I could see that the following protocols were allowed: 在此处输入图片说明

After I set this everything worked:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

You can attach eventHandler to ServicePointManager like this:

ServicePointManager.ServerCertificateValidationCallback = ForcedAuthDelegate;

and implementation of ForcedAuthDelegate should return true to accept connection:

        static bool ForcedAuthDelegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM