HTTP/2 request with client certificate sample code

My sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace TestHTTP2
{
class Program
{
static async Task Main(string[] args)
{
X509Certificate2 clientCert = GetClientCertificate();
Http2CustomHandler requestHandler = new Http2CustomHandler();
requestHandler.ClientCertificates.Add(clientCert);

using (var httpClient = new HttpClient(requestHandler))
{
//client.BaseAddress = new Uri(https://www.bing.com/);

HttpResponseMessage response = await httpClient.GetAsync(@https://jackyclientcer21.azurewebsites.net/);

if (response.IsSuccessStatusCode)
{
Console.WriteLine("HTTP2 is success!!");
}
else
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
}
}
Console.ReadLine();
}

private static X509Certificate2 GetClientCertificate()
{
X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
//X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

userCaStore.Open(OpenFlags.ReadOnly);
X509Certificate2 clientCertificate = null;
foreach (X509Certificate2 certificate in userCaStore.Certificates)
{
if (certificate != null)
{
Console.WriteLine(certificate.Subject);
Console.WriteLine(certificate.Thumbprint);
clientCertificate = certificate;
break;
}
}

return clientCertificate;
}
catch
{
throw;
}
finally
{
userCaStore.Close();
}
}
}

public class Http2CustomHandler : WinHttpHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
request.Version = new Version("2.0");
return base.SendAsync(request, cancellationToken);
}
}
}

HTH. 2021-2-9 by Jacky