使用证书进行Http请求

时间:2015-03-24 13:57:48

标签: c# web-services certificate vpn access-denied

所以,我与网络服务提供商建立了VPN连接。我还提供了.cer.pfx个文件。我在本地机器上安装了.cer。现在我正在尝试下载WSDL文件,但每当我创建HttpRequest时,我都会获得403(拒绝访问)。

X509Certificate Cert = X509Certificate.CreateFromCertFile("path");
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("url");
Request.ClientCertificates.Add(Cert);
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

我的实施有问题吗?

顺便说一句,为什么我需要.pfx?不仅.Cer文件足以提出请求吗?

更新

X509Certificate Cert = new X509Certificate();
Cert.Import(@"test.pfx", "123456", X509KeyStorageFlags.PersistKeySet);

1 个答案:

答案 0 :(得分:1)

查看此Microsoft支持文章。它有代码示例和几种不同的处理证书的方法

How to send a client certificate by using the HttpWebRequest and HttpWebResponse classes in Microsoft Visual C# .NET

您似乎缺少证书政策部分。

ServicePointManager.CertificatePolicy = new CertPolicy();

//Implement the ICertificatePolicy interface.
class CertPolicy: ICertificatePolicy
{
    public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate   certificate, WebRequest request, int certificateProblem)
    {
    // You can do your own certificate checking.
    // You can obtain the error values from WinError.h.

    // Return true so that any certificate will work with this sample.
    return true;
    }
}

还要确保cer文件的路径正确并且您使用Internet Explorer下载它。

//You must change the path to point to your .cer file location. 
X509Certificate Cert = X509Certificate.CreateFromCertFile("C:\\mycert.cer");

检查权限 -

  

您必须授予ASP.NET用户帐户对客户端证书的私钥的权限。若要授予ASP.NET用户帐户对客户端证书的私钥的权限,请使用WinHttpCertCfg.exe工具。