42

我正在使用 Google Analytics API,并按照这个 SO 问题设置 OAuth:https ://stackoverflow.com/a/13013265/1299363

这是我的 OAuth 代码:

public void SetupOAuth ()
{
    var Cert = new X509Certificate2(
        PrivateKeyPath, 
        "notasecret", 
        X509KeyStorageFlags.Exportable);
    var Provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, Cert)
    {
        ServiceAccountId = ServiceAccountUser,
        Scope = ApiUrl + "analytics.readonly"
    };
    var Auth = new OAuth2Authenticator<AssertionFlowClient>(Provider, AssertionFlowClient.GetState);
    Service = new AnalyticsService(Auth);
}

PrivateKeyPath 是 Google API Console 提供的私钥文件的路径。这在我的本地机器上完美运行,但是当我将它推送到我们的测试服务器时,我得到了

System.Security.Cryptography.CryptographicException: An internal error occurred.

使用以下堆栈跟踪(删除了不相关的部分):

System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +33
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +237
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +140
Metrics.APIs.GoogleAnalytics.SetupOAuth() in <removed>\Metrics\APIs\GoogleAnalytics.cs:36
Metrics.APIs.GoogleAnalytics..ctor(String PrivateKeyPath) in <removed>\Metrics\APIs\GoogleAnalytics.cs:31

所以它看起来好像在加载文件时遇到了问题。我检查了传入的 PrivateKeyPath,它指向正确的位置。

有任何想法吗?我不知道这是否是服务器、文件、代码或什么的问题。

4

5 回答 5

84

我想到的一件事是您的应用程序池的身份,请确保打开加载用户配置文件,否则加密子系统不起作用。

于 2013-01-10T17:59:18.013 回答
30

我正在加载我的p12文件

new X509Certificate2(
HostingEnvironment.MapPath(@"~/App_Data/GoogleAnalytics-privatekey.p12"), ....

即使File.Exists(filename)返回 true,我实际上也得到了 FileNotFoundException。

正如@Wiktor Zychla 所说,它就像启用一样简单Load User Profile

这是需要更改的设置的图像

只需右键单击 IIS 中“应用程序池”下的应用程序池,然后选择“高级设置”,您需要的设置大约是一半。

在此处输入图像描述

提示:我建议用这个来评论你的代码,以防止将来浪费时间,因为如果你以前从未遇到过它,它就会变得非常模糊。

  // If this gives FileNotFoundException see 
  // http://stackoverflow.com/questions/14263457/
于 2014-02-22T21:39:53.893 回答
13

也尝试指定 X509KeyStorageFlags

    var certificate = new X509Certificate2(KeyFilePath, KeyFilePassword, 
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | 
X509KeyStorageFlags.Exportable);
于 2014-05-14T09:58:49.720 回答
2

如上所述,您需要配置 IIS,但在我们的情况下,有时您需要检查以下文件夹的权限:

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

如果您设置X509KeyStorageFlags参数,它将在此文件夹中创建一个密钥文件。就我而言,此文件夹的权限有所不同。池帐户未添加到上述文件夹中。

于 2017-07-18T10:17:34.997 回答
-2

不,“File.Exists(...)”也在高级设置中吗?我有 3 个池,它们都为“加载用户配置文件”启用了 true。我认为我的问题可能与依赖项和 NuGet 包有关,因为代码作为控制台应用程序运行良好,但在 MVC 中给我带来了问题。

于 2014-03-04T10:19:58.507 回答