How to attach client certificate to AspNetCore TestServer api?

Viewed 655

I'm looking at Microsoft.AspNetCore.TestHost.TestServer in the Microsoft source code. There I see the CreateClient() property that is HttpClient objects.

So how do I attached the client certificate for Digitial Signature in xUnit Test?

HttpClient example would be this.

var x509Certificate2 = new X509Certificate();  // Pretend it contains certificate data already.

var httpClientHandler = new HttpClientHandler() {
    ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(x509Certificate2);

using (var httpClient = new HttpClient(httpClientHandler))
{
}

Now using the TestServer

var testServer = new TestServer();

testServer.CreateClient();  // How do I attached client certificate here?

So, how do we attach the client certificate here? For CreateClient()

Also, I can try to make do with implementing the HttpRequestMessage but it doesn't support that certificate option either.

1 Answers

You may try to use the testServer.SendAsync(...) method and just construct your HttpContext from there.

var result = await server.SendAsync(context =>
                                    {
                                        context.Connection.ClientCertificate = myClientCertificate;
                                        context.Request.Method = "POST";
                                     });

Just make sure to specify the Path and the Body as needed.

Related