代码之家  ›  专栏  ›  技术社区  ›  Perry Stathopoulos

X509Certificate2在调用Google API的Azure Webjobs中失败

  •  6
  • Perry Stathopoulos  · 技术社区  · 12 年前

    我有一个使用Azure WebJobs计划的控制台应用程序。尝试读取p12证书的私钥时,执行总是失败。有趣的是,我无法捕捉到例外,我不得不使用good old Console.WriteLine 以进行调试。

    以下是我的代码片段:

    var certificate = new X509Certificate2(data, "notasecret", X509KeyStorageFlags.Exportable);
    
    ServiceAccountCredential credential = new ServiceAccountCredential(
     new ServiceAccountCredential.Initializer(serviceAccountEmail)
     {
         Scopes = new[] { BigqueryService.Scope.Bigquery }
     }.FromCertificate(certificate));
    

    其他帖子提到,旗帜应该是 X509KeyStorageFlags.MachineKeySet 但不幸的是,这导致了Google API中的错误。它需要 X509KeyStorageFlags.Exportable 要设置的标志。

    有人能证实吗 X509KeyStorageFlags.可导出 在Azure网站和WebJobs上可用?

    2 回复  |  直到 12 年前
        1
  •  12
  •   Perry Stathopoulos    12 年前

    使用 X509KeyStorageFlags.Exportable 在IIS中不可用。我已经在自己的虚拟机上使用Azure Webjobs、Azure网站和IIS进行了尝试。当使用IISExpress时,它在开发环境中工作,因为进程在用户上下文中运行。

    因此,为了在IIS上下文(包括Webjobs)中工作,必须将其设置为 MachineKeySet 但是Google API将失败,因为它需要私钥。

    我的问题的解决方案实际上非常简单,创建一个控制台应用程序 X509Certificate2 具有的对象 Exportable 设置标志,然后调用 ToXmlString() 。下面是片段:

    var certificate = new X509Certificate2(data, "notasecret", X509KeyStorageFlags.Exportable); var xml = certificate.PrivateKey.ToXmlString(true);

    然后保存XML并使用该XML创建 RSACryptoServiceProvider 这样地:

    var rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(xmlKey);
    ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
     {
      Scopes = new[] { BigqueryService.Scope.Bigquery },
      Key = rsa
     });
    

    希望这对其他人有所帮助。

        2
  •  5
  •   Community Mohan Dere    9 年前

    此解决方案在Azure设置中有效。然而,我也找到了一个更简单的方法来满足我的需求。只需添加额外的标志,让每个人都很开心。。。

     var certificate = new X509Certificate2(data,"notasecret",
                           X509KeyStorageFlags.MachineKeySet | 
                           X509KeyStorageFlags.PersistKeySet | 
                           X509KeyStorageFlags.Exportable);
    

    我找到了 this solution