使用Azure App Services上的客户端证书提交SSL HttpWebRequests

时间:2018-02-02 01:56:25

标签: c# azure-web-sites

我尝试使用带有.NET的Azure Web App(App Service)中的客户端证书执行非常简单的HTTP / SSL请求。对于上下文,可以将日志写入Elasticsearch集群。

启用System.NetSystem.Net.Sockets的跟踪显示请求在尝试加载客户端证书的私钥时失败 - 该证书已在内存中加载

System.Net Information: 0 : [4064] SecureChannel#49205706 - Certificate is of type X509Certificate2 and contains the private key.
System.Net Information: 0 : [4064] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
System.Net Error: 0 : [4064] AcquireCredentialsHandle() failed with error 0X8009030D.
System.Net.Sockets Verbose: 0 : [0764] Socket#8628710::Dispose()
System.Net Error: 0 : [0764] Exception in the HttpWebRequest#53036123:: - The request was aborted: Could not create SSL/TLS secure channel.
System.Net Error: 0 : [0764] Exception in the HttpWebRequest#53036123::EndGetRequestStream - The request was aborted: Could not create SSL/TLS secure channel.

搜索AcquireCredentialsHandle() failed with error 0X8009030D表明它显然与证书存储中的权限有关 - 我使用。

我的猜测是,出于某种原因,AcquireCredentialsHandle尝试访问证书存储区,由于Azure Web Apps的沙盒环境,它无法执行此操作。我发现这很奇怪,因为SSL客户端身份验证应该足够通用,Azure一直在宣传应用服务作为生产就绪(为什么.NET甚至无论如何都会触摸它?)

它绝对不是特定于IIS的问题,因为它在常规可执行文件中失败了。以下代码在简单的webjob中失败。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace IFHM
{
    class Program
    {
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path));

            var req = (HttpWebRequest) WebRequest.Create("https://myapp.com");
            req.Method = "GET";
            req.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
            req.ClientCertificates.Add(new X509Certificate2("client.pfx"));
            try
            {
                var resp = req.GetResponse();
                var respStr = new StreamReader(resp.GetResponseStream()).ReadToEnd();
                Console.WriteLine(respStr);
            }
            catch (WebException e)
            {
                Console.Error.WriteLine(e);
                var errRespStr = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
                Console.WriteLine(errRespStr);
            }

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您似乎需要将.pfx文件上传到Azure WebApp,并首先使其可以访问您的应用程序代码。您可以使用 WEBSITE_LOAD_CERTIFICATES 应用设置进行此操作。

您可以从the Wingtip sample

获取详细步骤和演示代码