我正在尝试连接到一个使用TLS和客户端证书验证的服务器。以下是代码片段:
async Task TestClientCertAuth()
{
int iWinInetError = 0;
Uri theUri = new Uri("http://xxx-xxx");
try
{
using (HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter())
{
// Task<Certificate> GetClientCertificate() displays a UI with all available
// certificates with and returns the user selecter certificate. An
// oversimplified implementation is included for completeness.
baseProtocolFilter.ClientCertificate = await GetClientCertificate();
baseProtocolFilter.AllowAutoRedirect = false;
baseProtocolFilter.AllowUI = false;
using (HttpClient httpClient = new HttpClient(baseProtocolFilter))
using (HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, theUri))
using (HttpResponseMessage httpResponse = await httpClient.SendRequestAsync(httpRequest))
{
httpResponse.EnsureSuccessStatusCode();
// Further HTTP calls using httpClient based on app logic.
}
}
}
catch (Exception ex)
{
iWinInetError = ex.HResult & 0xFFFF;
LogMessage(ex.ToString() + " Error code: " + iWinInetError);
throw;
}
}
// Task<Certificate> GetClientCertificate() displays a UI with all available
// certificates with and returns the user selecter certificate. An
// oversimplified implementation is included for completeness.
private async Task<Certificate> GetClientCertificate()
{
IReadOnlyList<Certificate> certList = await CertificateStores.FindAllAsync();
Certificate clientCert = null;
// Always choose first enumerated certificate. Works so long as there is only one cert
// installed and it's the right one.
if ((null != certList) && (certList.Count > 0))
{
clientCert = certList.First();
}
return clientCert;
}
SendRequestAsync调用抛出HRESULT 0x80072F7D的异常 - 我相信这意味着ERROR_INTERNET_SECURITY_CHANNEL_ERROR。服务器证书信任没有问题,客户端证书已安装在应用程序本地存储中,并且我可以使用CertificateStores.FindAllAsync检索它。查看SSL跟踪,我发现客户端证书未被发送。
如果将HttpBaseProtocolFilter.AllowUI设置为true,则不会发生上述问题。在这种情况下,SendRequestAsync调用会导致显示一个UI,询问是否同意使用客户端证书。一旦在此对话框上选择“允许”,我就可以在跟踪中看到客户端证书和证书验证消息被发送,并且连接成功建立。
问题:应用程序代码已经处理了用户的证书选择。我想知道是否有办法以编程方式指定同意使用客户端证书。因为启用AllowUI会导致其他副作用 - 例如,如果服务器返回带有WWW-Authenticate: Basic标头的401 HTTP代码,则基础协议过滤器会弹出自己的UI以接受用户凭据,而不给调用方处理它的机会。由于我已经使用自己的UI选择了客户端证书并获得了用户凭据,所以希望避免上述两个UI。谢谢。