我正在尝试在我的应用程序中实现 Https 客户端身份验证,但找不到有关如何执行此操作的任何文档。
浏览 MSDN 文档我想到了这个
// Certificate file in DER format (.cer or .p7b)
string CountriesFile = @"Assets\https-client.keystore.cer";
StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await InstallationFolder.GetFileAsync(CountriesFile);
// Read the file into a buffer
IBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(file);
// Create the Certificate object
Certificate ClientCert = new Certificate(buffer);
HttpBaseProtocolFilter aHBPF = new HttpBaseProtocolFilter();
aHBPF.ClientCertificate = ClientCert;
// Create our http client and send the request.
HttpClient httpClient = new HttpClient(aHBPF);
HttpResponseMessage response = await httpClient.SendRequestAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);
我将这段代码放在一起,查看 HttpClient 的文档, HttpBaseProtocolFilter和 Certificate 。假设我应该拥有所需格式的证书并将文件读入 Certificate
类。
上面的代码不起作用并抛出此错误
An exception of type 'System.ArgumentException' occurred in MyLib.DLL but was not handled in user code
WinRT information: The certificate specified is missing the required private key information.
我已经测试了我的服务器设置,它通过浏览器与客户端身份验证一起使用,这使我得出两个可能的结论。
- 证书文件的格式错误(尽管我希望在构造
Certificate
类时抛出异常)。 - 这不是我们想要的方式!
有人知道应该怎么做吗?
最佳答案
看来您必须在用户级别安装证书,然后才能在 Windows 应用商店应用程序中有效地使用它进行客户端身份验证
// Needs to be a PKCS12 (p12/pfx) file
string certPath = @"Assets\https-client.keystore.p12";
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(certPath);
IBuffer buffer = await FileIO.ReadBufferAsync(file);
string certData = CryptographicBuffer.EncodeToBase64String(buffer);
// Will ask the user if they want this app to install the certificate if its not already installed.
await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync(
certData,
"PASSWORD",
ExportOption.NotExportable,
KeyProtectionLevel.NoConsent,
InstallOptions.None,
"MyFriendlyName");
现在证书已安装,我们可以在证书存储中使用它。
var certificate = await CertificateStores.FindAllAsync(new CertificateQuery() { FriendlyName = "MyFriendlyName" });
ClientCert = certificate.Single();
HttpBaseProtocolFilter aHBPF = new HttpBaseProtocolFilter();
aHBPF.ClientCertificate = ClientCert;
// Create our http client and send the request.
HttpClient httpClient = new HttpClient(aHBPF);
HttpResponseMessage response = await httpClient.SendRequestAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);
我希望能够使证书仅对应用程序可用,并且如果我找到一种方法,我会更新此答案。
关于c# - Windows 应用商店应用程序 - C# - Https 客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287586/