runtime icon indicating copy to clipboard operation
runtime copied to clipboard

ServicePoint retrieved via FindServicePoint does not contain server certificate

Open bojanrajkovic opened this issue 8 years ago • 5 comments

A typical way to obtain the server certificate after making a request via HttpClient is to use ServicePointManager.FindServicePoint with the URI and grab the Certificate property off of that.

This works fine in .NET 4.5, as evidenced by this fragment from a workbook:

image

However, in a .NET Core application, this doesn't work:

image

You can also see the attached project in certificate-test.zip. It contains a sample you can download and dotnet run.

dotnet --info output:

.NET Command Line Tools (2.1.4)

Product Information:
 Version:            2.1.4
 Commit SHA-1 hash:  5e8add2190

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.4\

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.5
  Build    : 17373eb129b3b05aa18ece963f8795d65ef8ea54

bojanrajkovic avatar Jan 23 '18 03:01 bojanrajkovic

Using a custom server validation callback does work, but in order to hold on to the certificate after the request is complete (possibly even after the callback is complete), you must make a copy via Export.

Unsurprisingly, creating a TcpClient, wrapping the stream in an SslStream, calling AuthenticateAsClient, and then checking the RemoteCertificate property also works.

bojanrajkovic avatar Jan 23 '18 04:01 bojanrajkovic

ServicePoint is not supported on .NET Core. If you need to grab the server certificate using HttpClient, you can use the ServerCertificateCustomValidationCallback in HttpClientHandler:

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netcore-2.0

The server certificate is passed into this callback.

cc: @karelz @geoffkizer

davidsh avatar Jan 23 '18 15:01 davidsh

Yep, I figured that out, but it would be good to either document this, or make the ServicePoint-related code throw not supported exceptions on .NET Core. As it is, it seemed to be in a half-working state, because other parts of the SP were properly set, just not the certificate.

bojanrajkovic avatar Jan 23 '18 16:01 bojanrajkovic

I guess we could document that it is deprecated / compat-only on https://github.com/dotnet/platform-compat/issues

karelz avatar Jan 23 '18 16:01 karelz

Triage: We need the documentation. Mention alternative: HttpClient with certificate validation callback.

karelz avatar Oct 10 '19 17:10 karelz