【问题标题】:Invalid provider type specified when trying to access google analytics尝试访问谷歌分析时指定的提供商类型无效
【发布时间】:2018-06-11 13:51:02
【问题描述】:

每当我们尝试访问 API 以获取当前用户编号时,我们都会不断收到以下错误消息。我已经尝试了一些事情,但无法深入了解这一点。任何人都可以阐明什么是错误/缺失的吗?

我应该指出,因此在我的本地 PC 上运行得很好,但在服务器上却失败了。

这是错误:

ConnectToAnalytics 错误: System.Security.Cryptography.CryptographicException:提供程序无效 指定的类型。在 System.Security.Cryptography.Utils.CreateProvHandle(CspParameters 参数,布尔随机密钥容器)在 System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters 参数, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) 在 System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() 在 System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters 参数, Boolean useDefaultKeySize) at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() 在 Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.FromCertificate(X509Certificate2 证书)在 C:\Users\mdril\Documents\GitHub\google-api-dotnet-client\Src\GoogleApis.Auth.DotNet4\OAuth2\ServiceAccountCredential.cs:line 100 在 Core.ConnectToAnalytics()

运行代码时抛出此错误:

Public Shared Function GetRealtimeUsers() As String
    Try
        'realtime on site
        Dim gsService As AnalyticsService = Core.ConnectToAnalytics
        Dim RequestRealtime As DataResource.RealtimeResource.GetRequest = gsService.Data.Realtime.[Get]([String].Format("ga:{0}", "xxxxx"), "rt:activeUsers")
        Dim feed As RealtimeData = RequestRealtime.Execute()

        Return Int(feed.Rows(0)(0)).ToString()
    Catch ex As Exception
        Return "QUOTA USED"
    End Try

错误在这里:RequestRealtime.Execute()

供参考 - 这是连接脚本:

Public Shared Function ConnectToAnalytics() As AnalyticsService
    Try
        Dim scopes As String() = New String() {AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsEdit, AnalyticsService.Scope.AnalyticsManageUsers, AnalyticsService.Scope.AnalyticsReadonly}
        Dim keyFilePath = HttpContext.Current.Server.MapPath("\xxx.p12")
        Dim serviceAccountEmail = "xxx"
        Dim certificate = New X509Certificate2(keyFilePath, "xxxx", X509KeyStorageFlags.Exportable)
        Dim credential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {.Scopes = scopes}.FromCertificate(certificate))
        Return New AnalyticsService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = "Client for xxx"})
    Catch ex As Exception
        Core.SendAdminStatusReport("ConnectToAnalytics error: " & ex.ToString)
        Throw ex
    End Try
End Function

【问题讨论】:

  • 这是一个密码学错误。请编辑您的问题并添加 stackoverflow.com/help/mcve 这里没有足够的信息来查找问题。
  • 尽我所能更新

标签: asp.net google-api google-analytics-api google-api-dotnet-client service-accounts


【解决方案1】:

我在这篇文章中找到了解决方法:

https://www.daimto.com/azure-with-service-accounts-in-c/

改变这一行

var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);

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

解决了我的问题

【讨论】:

  • 在服务环境(而不是作为用户应用程序)中使用证书时,这是一个特别好的主意
【解决方案2】:

如果没有看到您的代码,很难知道您的问题是什么,但这是我的服务帐户身份验证代码

   /// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
    public static AnalyticsreportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
            if (string.IsNullOrEmpty(serviceAccountEmail))
                throw new Exception("ServiceAccountEmail is required.");                

            // For Json file
            if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
            {
                GoogleCredential credential;
                using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }

                // Create the  Analytics service.
                return new AnalyticsreportingService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Analyticsreporting Service account Authentication Sample",
                });
            }
            else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
            {   // If its a P12 file

                var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = scopes
                }.FromCertificate(certificate));

                // Create the  Analyticsreporting service.
                return new AnalyticsreportingService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Analyticsreporting Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {                
            throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
        }
    }
}

ServiceAccount.cs 窃取的代码

【讨论】:

    【解决方案3】:

    我设法解决了这个问题 - 我在正确的线路上使用了根证书,结果发现我错过了一个。这些可以在这里找到:

    https://pki.goog/

    我不记得我在哪里找到的,但是将下面的代码添加到 webconfig 帮助我找出了我丢失的证书:

     <system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.Net">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.HttpListener">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Sockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Cache">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add
       name="System.Net"
       type="System.Diagnostics.TextWriterTraceListener"
        initializeData="System.Net.trace.log"
       traceOutputOptions = "ProcessId, DateTime"
                />
    </sharedListeners>
    <switches>
      <add name="System.Net" value="Verbose" />
      <add name="System.Net.Sockets" value="Verbose" />
      <add name="System.Net.Cache" value="Verbose" />
      <add name="System.Net.HttpListener" value="Verbose" />
    </switches>
    

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 2021-11-27
      • 2014-04-30
      • 2018-06-22
      • 2013-03-24
      • 2019-07-07
      • 2015-09-28
      • 2019-02-03
      相关资源
      最近更新 更多