将证书添加到HttpWebRequestin C#

时间:2015-12-06 15:14:25

标签: c# x509 azure-cloud-services

我正在尝试将证书存储中的证书添加到HttpWebRequest对象中。证书从商店成功获取并添加了HttpWebRequestobject。但是当发送请求时,在恢复结束时证书不存在。不确定两者之间发生了什么。这是我的代码,它获取证书,然后将其发送到接收服务器。该过程用于基于证书的身份验证。(我正在尝试使用服务器验证自己)

X509Store store = new X509Store("My", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
// Look for the first certificate that is named Cartus-to-Microsoft.
// Look in the local machine store.
X509CertificateCollection col = (X509CertificateCollection)store.Certificates.Find(X509FindType.FindBySubjectName, certName, true);
X509Certificate cert = null;
try
{
    if(col.Count>0)
        cert = col[0];
}
catch (Exception ex)
{
    throw new Exception("Certificate not Found!");
}

//HttpWebRequest req = null;
HttpWebResponse rsp = null;
string uri = "http://relofileservice.azurewebsites.net/api/datasync/reloPostService"; //"http://localhost:64952/api/datasync/reloPostService";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

//Add payload to request
var data = Encoding.ASCII.GetBytes(json);
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "application/x-www-forum-urlencoded";
req.ContentLength = data.Length;
using (var stream = req.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
//Build The request Header
req.KeepAlive = false;
req.UserAgent = "Cartus API Client";
req.ClientCertificates.Add(cert);
System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; };

Trace.TraceInformation("Certificate added to rquest");
try
{
    //Send the request and receive response.
    rsp = (HttpWebResponse)req.GetResponse();
}
catch (Exception Ex)
{
    Trace.TraceError("GetResponse Error Message: " + Ex.Message + ". GetResponse Error StackTrace: " + Ex.StackTrace);
}

1 个答案:

答案 0 :(得分:0)

想出来。在发送证书之前,需要完成两个步骤。没有一个博客或文档解释了这两个步骤。有趣的是,在提出的解决方案中,重要的部分总是被遗漏。无论如何,这是解决方案的最后花絮:

  1. 确保客户端证书位于个人存储区中。
  2. 分配权限以读取尝试从商店读取证书的用户帐户的私钥。
  3. 代码明智:

    X509Store store = new X509Store("My", StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    
    X509Certificate2Collection col = (X509Certificate2Collection)store.Certificates.Find(X509FindType.FindBySubjectName, certName, true);
    X509Certificate2 cert = null;
    try
    {
        if(col.Count>0)
        cert = col[0];
    }
    catch (Exception ex)
    {
        throw new Exception("Certificate not Found!");
    }
    
    store.Close();
    

    和Voila !!!