使用带有x509证书的WebClient返回403

时间:2014-06-02 12:23:39

标签: c# ssl https webclient x509

我在证书存储中注册了证书,可以访问需要此证书的网站,并且可以使用证书“登录”。我试图在代码中做同样的事情。

证书从存储中正确加载,但在尝试获取相关网站时,我仍然获得403(禁止)。有什么想法吗?

这是代码。

首先获得证书:

    public static X509Certificate2 GetCertificate()
    {
        const string certStore = "CurrentUser";

        var store = new X509Store(StoreName.Root);

        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = store.Certificates;
        X509Certificate2 certificate = null;

        bool found = false;
        string certsFound = "";

        foreach (X509Certificate2 cert in certCollection)
        {
            certsFound += cert.SubjectName.Name + Environment.NewLine;
            certificate = cert;

            if (cert.Subject.Contains("CertProviderName"))
            {
                found = true;

                break;
            }

        }

        if (!found)
            throw new ApplicationException("Certificate not found!" + Environment.NewLine + "Certs found: " +
                                           certsFound + Environment.NewLine + "CertStore=" + certStore);

        return certificate;
    }

创建自定义webclient:

public class MyWebClient : WebClient
{
    public X509Certificate2 Certificate { get; set; }
    public readonly CookieContainer CookieContainer = new CookieContainer();
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = (HttpWebRequest) base.GetWebRequest(address);

        request.CookieContainer = CookieContainer;

        request.ClientCertificates.Add(Certificate);

        return request;
    }

}

...并尝试访问网站:

    public static void GetPage()
    {
        var cert = GetCertificate();

        var client = new MyWebClient();
        client.Certificate = cert;

        var page = client.DownloadString(@"https://the.website.com");
    }

在“client.DownloadString”上失败了403(Forbidden)。

0 个答案:

没有答案