gpt4 book ai didi

c# - Windows 应用商店应用程序 - C# - Https 客户端身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:16 24 4
gpt4 key购买 nike

我正在尝试在我的应用程序中实现 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 的文档, HttpBaseProtocolFilterCertificate .假设我应该拥有所需格式的证书并将文件读入 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.

我已经测试了我的服务器设置,它通过浏览器与客户端身份验证一起工作,这使我得出两个可能的结论。

  1. 证书文件格式错误(尽管我希望在构造 Certificate 类时抛出异常)。
  2. 这不是预期的方式!

有人知道应该怎么做吗?

最佳答案

看来您必须先在用户级别安装证书,然后才能有效地将其用于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com