-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebClientWinRT.cpp
71 lines (53 loc) · 2.19 KB
/
WebClientWinRT.cpp
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
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Web.Http.Filters.h>
#include <winrt/Windows.Security.Cryptography.Certificates.h>
#include <iostream>
#pragma comment(lib, "windowsapp.lib")
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Security::Cryptography::Certificates;
using namespace Windows::Web::Http;
/** Returns the first clientAuth certificate with private key found in the Windows cert. store. */
Certificate GetFirstClientAuthCert() {
CertificateQuery query;
{
query.IncludeExpiredCertificates(false);
Collections::IVector<hstring> eku = query.EnhancedKeyUsages();
eku.Append(L"1.3.6.1.5.5.7.3.2"); // clientAuth OID
query.StoreName(StandardCertificateStoreNames::Personal()); // "MY" store for current user (default)
}
// search for first matching certificate
Collections::IVectorView<Certificate> certs = CertificateStores::FindAllAsync(query).get();
for (Certificate cert : certs) {
if (!cert.HasPrivateKey())
continue;
std::wcout << L"Client certificate: " << std::wstring(cert.Subject()) << L"\n\n";
return cert;
}
throw hresult_error(winrt::impl::error_fail, L"no clientAuth cert found");
}
void HttpGetWinRT(std::wstring url, Certificate clientCert) {
Filters::HttpBaseProtocolFilter filter;
filter.ClientCertificate(clientCert);
// perform HTTP request with client authentication
HttpClient client(filter);
HttpResponseMessage response = client.GetAsync(Uri(url)).get();
response.EnsureSuccessStatusCode();
hstring message(response.Content().ReadAsStringAsync().get());
std::wcout << std::wstring(message);
}
int wmain(int argc, wchar_t* argv[]) {
init_apartment();
std::wstring hostname = L"localhost:443"; // default
if (argc > 1)
hostname = argv[1];
try {
auto clientCert = GetFirstClientAuthCert();
std::wcout << "\n\nHTTP request using WinRT HttpClient:\n";
HttpGetWinRT(L"https://" + hostname, clientCert);
}
catch (hresult_error const& ex) {
std::wcerr << L"ERROR: " << std::wstring(ex.message()) << std::endl;
}
return 0;
}