dotnet/runtime

.net 8, HttpClient, adding ssl cert after first use, the cert does not get used

Open

#96494 opened on Jan 4, 2024

View on GitHub
 (18 comments) (0 reactions) (0 assignees)C# (17,886 stars) (5,445 forks)batch import
area-System.Net.Httpdocumentationhelp wanted

Description

Description

I do not know how to verify this behavior other than the one server (webhooks) i am connecting to. But, based on my experience, it seems that in .net 8, if an HttpClient uses .GetAsync() or .PostAsync(), and then adds an ssl certificate to the handler, the cert does not get used for following calls. The same worked in .net 7.

Reproduction Steps

I do not know how to show if an ssl certificate is being used. The idea is simple, add the ssl certificate after the first request:

Imports System.Net.Http
Imports System.Security.Cryptography.X509Certificates

Public Class Form1
	Private Async Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
		Dim Http_Client_Handler As New HttpClientHandler
		Dim Http_Client As New HttpClient(Http_Client_Handler)

		Using Response As HttpResponseMessage = Await Http_Client.GetAsync($"https://example.com")
			Debug.WriteLine($"Result: {Await Response.Content.ReadAsStringAsync}")
			Debug.WriteLine($"Status: {Response.StatusCode}")
		End Using

		' Add SSL Certificate
		Using X509_Store As New X509Store(StoreLocation.LocalMachine)
			X509_Store.Open(OpenFlags.ReadOnly)
			Http_Client_Handler.ClientCertificates.Add(X509_Store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, $"CN={ ...}", True)(0))
		End Using

		Using Response As HttpResponseMessage = Await Http_Client.GetAsync($"https://example.com")
			Debug.WriteLine($"Result: {Await Response.Content.ReadAsStringAsync}")
			Debug.WriteLine($"Status: {Response.StatusCode}")
		End Using
	End Sub
End Class

Expected behavior

The second connection should work without issue.

Actual behavior

The second request returns a 400, with the error that no ssl certificate was used.

Regression?

This worked in .net 7.

Known Workarounds

Add the ssl certificate first, or use a second HttpClient.

Configuration

Windows 10, .net 8, x64.

Other information

No response

Contributor guide