【问题标题】:502 error when generating X509Certificate2 from p12 certificate in Azure Websites for Google API在 Azure 网站中为 Google API 从 p12 证书生成 X509Certificate2 时出现 502 错误
【发布时间】:2015-05-08 10:19:25
【问题描述】:

我正在使用This GoogleJsonWebToken 类来生成一个访问令牌,以便与对 Google 日历 API 的 json 调用一起使用。当我使用以下内容(使用我的实际服务帐户电子邮件)时,它在我的开发机器上的 IIS Express 中运行良好:

string p12Path = HttpContext.Current.Server.MapPath("~/App_Data/certificate.p12");
var auth = GoogleJsonWebToken.GetAccessToken("uniquestring@developer.gserviceaccount.com",
                                             p12Path,
                                             "https://www.googleapis.com/auth/calendar");
string Token = auth["access_token"];

为了测试这一点,我只是在我的 cshtml razor 视图中调用@Token。当我将此发布到我的 Azure 网站时,它不起作用。如果我不修改GoogleJsonWebToken 类,我会得到一个非常无用的502 - Web server received an invalid response while acting as a gateway or proxy server.,没有其他信息。

经过一些谷歌搜索后,我发现this SO post 这是一个类似的问题。所以我尝试了他们的解决方案,当从我的 Azure 网站运行时,我得到了System.Security.Cryptography.CryptographicException: The system cannot find the file specified.。当它从我的开发机器上运行时,我得到System.Net.WebException: The remote server returned an error: (400) Bad Request.,我认为这是因为使用该解决方案CspKeyContainerInfo.KeyContainerNamenull,而在我的开发机器上运行时原始未修改的类给了我类似{C0E26DC5-5D2C-4C77-8E40-79560F519588} 的东西,这是随机的每次生成,这个值在签名的过程中使用。

然后我找到了this SO post,但该解决方案产生的结果与上一个解决方案相同。

我也尝试了X509KeyStorageFlags 的大多数不同组合,但均无济于事。

我怎样才能自己生成CspKeyContainerInfo.KeyContainerName 或以其他方式成功生成X509Certificate2

【问题讨论】:

    标签: c# asp.net azure google-api


    【解决方案1】:

    我在this MSDN forum post 上找到了解决方案。基本上我需要设置X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet,正如我在我提到的第一篇 SO 帖子中所读到的那样,然后我需要在我的 CspParamaters 中设置Flags = CspProviderFlags.UseMachineKeyStore

    我已经发布了我的full solution on GitHub

    【讨论】:

    • 是的,这是为我做的
    • 完全相同的问题。用 X509KeyStorageFlags.Exportable 替换 X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.MachineKeySet 成功了。非常感谢。
    • 您知道这是否存在安全隐患吗?我相信对于 Azure Web 应用程序,每台物理(或虚拟?)机器有多个租户。
    • @BenjiFB 如果您担心安全隐患,您将不会使用 Azure Web 应用程序。每个物理主机确实有多个租户,但它们不在同一个虚拟机中。
    【解决方案2】:

    首先,您应该将 p12 文件添加到资源中:

    右键项目-属性-资源-添加资源 然后将这行代码用于证书

    var certificate = new X509Certificate2((byte[])Properties.Resources.ResourceManager.GetObject(ResourceName), "!password!", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多