Azure函数中的运行时错误加载证书

时间:2016-10-25 12:37:35

标签: c# azure azure-functions

我想创建一个Azure函数(C#API Generic HTTP)方法,将文件上传到Office365 Sharepoint文档库。

由于OneDrive API允许我上传大文件(使用守护程序进程和证书身份验证),因此我成功地使用C#控制台应用程序实现了目标。

现在的想法是将代码移动到Azure功能中。 但是,在加载pfx证书时,我在函数运行期间收到错误。

True

X509Certificate2 cert = new X509Certificate2(certfile,“”);抛出异常  System.Security.Cryptography.CryptographicException:系统找不到指定的文件。

这真的很奇怪,因为文件存在于指定的路径上(我在方法中使用File.Exists()检查:)) 这个错误可能与support.microsoft.com/en-us/kb/948154有关吗?我该如何解决这个问题?

祝你好运, 延

2 个答案:

答案 0 :(得分:12)

添加X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable到构造函数。这段代码适合我:

using System.Net;
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    string certfile = System.IO.Path.Combine(Environment.ExpandEnvironmentVariable‌​s("%HOME%"), @"site\wwwroot\HttpTriggerCSharp4\myCertFile.pfx");        
    log.Info(certfile); 
    log.Info(System.IO.File.Exists(certfile).ToString());
    X509Certificate2 cert = new X509Certificate2(certfile, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);     
    log.Info(cert.Thumbprint);

答案 1 :(得分:2)

  1. 通过门户网站上传您的证书: 功能应用设置 - &gt;转到应用服务设置 - &gt; SSL证书 - &gt;上传证书

  2. 通过Azure门户上传证书后,您需要添加名为WEBSITE_LOAD_CERTIFICATES的appsetting(也通过门户网站),并将此值设置为上传证书的指纹。如果您愿意,这可以是以逗号分隔的多个指纹列表,甚至*可以加载所有上传的证书

  3. 代码:

    using System.Net;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
    {
        var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "Your thumb", false);