如何使用HttpWebRequest和IISExpress发送客户端证书进行调试

use*_*180 5 .net httpwebrequest client-certificates iis-express

我有一些代码从页面请求中提取客户端证书.这是"MyPage.aspx"中的代码.

string someparam = this.Request.Params["someparam"];
if (!String.IsNullOrWhiteSpace(someparam) && this.Page.Request.ClientCertificate.IsPresent)
{
    try
    {
        X509Certificate2 x509Cert2 = new X509Certificate2(this.Page.Request.ClientCertificate.Certificate);
        //
        // Code for verifying the x509Cert2
        //
    }
    catch (Exception) { }
}
Run Code Online (Sandbox Code Playgroud)

现在我想在我的本地环境中测试Visual Studio中的代码.为此,我安装了IISExpress以通过https获得可信通信.到现在为止还挺好.问题是我的发送客户端证书的测试代码似乎不起作用.ClientCertificate.IsPresent = false在服务器上.

以下是测试代码.证书是.pfx文件.

var request = (HttpWebRequest)WebRequest.Create("https://localhost:44300/MyPage.aspx?someparam=222");
request.Method = "POST";

X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySerialNumber, "XXXTHESERIALNUMBERXXX", true);
certFromStore = col[0];
store.Close();
request.ClientCertificates.Add(certFromStore);

HttpWebResponse reqWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader reqResponseStream = new StreamReader(reqWebResponse.GetResponseStream(), Encoding.UTF8);

String resultHtml = reqResponseStream.ReadToEnd();

reqWebResponse.Close();
reqResponseStream.Close();
Run Code Online (Sandbox Code Playgroud)

运行测试代码时没有错误.证书已从商店正确加载,并成功添加到request.ClientCertificates集合中.但在MyPage.aspx中,无法从页面请求中提取证书.

有没有人知道我错过了什么?

小智 2

您需要在 IIS Express 实例的配置文件中指定参数,该文件位于
C:\Users\[username]\Documents\IISExpress\config\applicationhost.config

您应该寻找安全元素。

该元素控制 IIS 服务器是否接受客户端证书。将启用属性设置为 true 可以实现以下目的:

iisClientCertificateMappingAuthentication enabled="true"

access 元素控制如何处理访问。sslFlags 属性控制如何处理客户端证书。由于某种原因,我让 IIS 实际向请求传递证书的唯一方法是将 sslFlags 设置为值 SslNegotiateCert,如下所示:

access sslFlags="SslNegotiateCert"