【发布时间】:2019-04-16 05:42:43
【问题描述】:
如何使用特定证书从 Azure Function 中调用 HTTPS 站点以建立 HTTPS 连接?
我有一个需要使用证书与远程服务器通信的 Azure 函数。远程服务器是银行。
安装证书并在本地运行 Azure Function Emulator 并建立连接。
上传到 Azure 我收到了这条消息
The SSL connection could not be established, see inner exception. Authentication failed, see inner exception.
我尝试将证书包含在 Azure Function SLL 下 我将证书链中的所有证书都安装为公共证书 (.cer) 和私有证书 (.pfx)
尝试使用指纹获取证书失败。
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = store.Certificates;
foreach (var certificate2 in certificates)
{
if (certificate2.Thumbprint.ToLower() == thumbprint.ToLower())
{
return certificate2;
}
}
}
在这种情况下,我也尝试循环而不是使用内置函数查找证书以使用 Tumbprint 查找证书
当这不起作用时,我将证书 (.pfx) 作为文件提供。
获取证书有效。
certificate = new X509Certificate2(filename, password, X509KeyStorageFlags.MachineKeySet);
Azure 函数需要 X509KeyStorageFlags.MachineKeySet,但运行本地 Azure Function Emulator 时不需要
RestSharp 在 Azure Function Emulator 中运行
var client = new RestClient(BaseUrl)
{
Timeout = 180000,
ClientCertificates = new X509CertificateCollection() { cert }
};
client.AddDefaultHeader("Content-type", "application/json");
var request = new RestRequest(Query, Method.POST);
request.Parameters.Clear();
request.AddParameter("application/json", jsonSwish, ParameterType.RequestBody);
IRestResponse response = await client.ExecuteTaskAsync(request);
我收到“无法建立 SSL 连接...”
我在创建客户端之前添加了这个,但它没有解决问题
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
然后我创建了一个简单的 PHP,它在输入中包含 HTTP,并使用 CURL 和所需的证书作为 CURL 的参数创建 HTTPS 输出。 这行得通,但却是一个丑陋的解决方案。
如何使用特定证书从 Azure Function 中调用 HTTPS 站点以建立 HTTPS 连接?
【问题讨论】:
-
正如错误所说
see inner exception。什么是内部异常?发布 full 异常,包括其调用堆栈和任何内部异常。您可以使用Exception.ToString()轻松获得。这将告诉您问题是 TLS1.2(现在所有主要提供商都需要 TLS1.2)还是证书问题 -
您不需要从 4.6 开始也不应该设置
ServicePointManager.SecurityProtocol,只要您运行的是受支持的操作系统版本.运行时将选择使用操作系统默认值,这意味着一旦 TLS1.3 可用,它将选择它。即使您使用较旧的运行时,允许SecurityProtocolType.Tls也是一个坏主意 - 该协议被认为是不安全的。
标签: c# azure ssl azure-functions restsharp