如何使用服务帐户来访问谷歌Analytics API V3使用.NET C#? [英] How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?

查看:507
本文介绍了如何使用服务帐户来访问谷歌Analytics API V3使用.NET C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这个问题一直是previously问,但很少在例如code的方式,所以我再次询问,但与方向中的至少一点点。

在搜索的时间,我想出了下面的部分实现。

 命名空间GoogleAnalyticsAPITest.Console
{
    使用System.Security.Cryptography.X509Certificates;
    使用DotNetOpenAuth.OAuth2;
    使用Google.Apis.Analytics.v3;
    使用Google.Apis.Analytics.v3.Data;
    使用Google.Apis.Authentication.OAuth2;
    使用Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

    类节目
    {
        静态无效的主要(字串[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            字符串范围= Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString()TOLOWER()。
            字符串scopeUrl =htt​​ps://www.googleapis.com/auth/+范围;
            常量字符串ServiceAccountId =nnnnnnnnnnn.apps.googleusercontent.com;
            常量字符串ServiceAccountUser =nnnnnnnnnnn@developer.gserviceaccount.com;
            AssertionFlowClient客户端=新AssertionFlowClient(
                GoogleAuthenticationServer.Description,新X509Certificate2(@7039572692013fc5deada350904f55bad2588a2a-privatekey.p12,notasecret,X509KeyStorageFlags.Exportable))
            {
                范围= scopeUrl,
                ServiceAccountId = ServiceAccountId //,ServiceAccountUser = ServiceAccountUser
            };
            IAuthorizationState状态= AssertionFlowClient.GetState(客户端);
            AnalyticsService服务=新AnalyticsService(验证);
            字符串配置文件ID =GA:XXXXXXXX;
            字符串的startDate =2010-10-01;
            字符串结束日期=2010-10-18;
            字符串指标=GA:访问;
            DataResource.GaResource.GetRequest请求= service.Data.Ga.Get(配置文件ID,的startDate,结束日期,指标);
            request.Dimensions =GA:日期;
            GaData数据= request.Fetch();
        }
    }
}
 

我有几个问题。在的DotNetOpenAuth日志中看到一个invalid_scope响应号召 AssertionFlowClient.GetState(客户端)结果

  

2012年10月19号13:27:36272(GMT-4)[8]信息DotNetOpenAuth - DotNetOpenAuth,版本= 4.0.0.11165,文化=中性公钥= 2780ccd10d57b246(官方)   2012年10月19日13:27:36284(GMT-4)[8] DEBUG DotNetOpenAuth.Messaging.Channel - preparing发送AssertionFlowMessage(2.0)的消息。   2012年10月19日13:27:36294(GMT-4)[8]信息DotNetOpenAuth.Messaging.Channel - prepared传出AssertionFlowMessage(2.0)消息的https://accounts.google.com/o/oauth2/token~~V :     grant_type:断言     assertion_type: http://oauth.net/grant_type/jwt/1.0/bearer     断言:(一堆连接codeD字符放在这里)

     

2012年10月19号13:27:36296(GMT-4)[8] DEBUG DotNetOpenAuth.Messaging.Channel - 发送AssertionFlowMessage请求。   2012年10月19日13:27:36830(GMT-4)[8] DEBUG DotNetOpenAuth.Http - HTTP POST 的https:/ /accounts.google.com/o/oauth2/token   2012年10月19日13:27:36954(GMT-4)[8]错误DotNetOpenAuth.Http - 从WebException 的https:/ /accounts.google.com/o/oauth2/token :   {    错误:invalid_scope   }

我已经试过指定一个或两个ServiceAccountId和ServiceAccountUser没有运气。

其次,即使我得到一个IAuthorizationState,我不知道我是如何得到一个可以传递给AnalyticsService构造一个IAuthenticator。

下面是我用它来使DotNetOpenAuth记录web.config中。

 < XML版本=1.0&GT?;
<结构>
  < configSections>
    <节名称=log4net的TYPE =log4net.Config.Log4NetConfigurationSectionHandler,log4net的,版本= 1.2.10.0,文化=中性公钥= 1b44e1d426115821/>
    <! - <节名称=log4net的TYPE =log4net.Config.Log4NetConfigurationSectionHandlerrequirePermission =FALSE/>  - >
    < sectionGroup名=dotNetOpenAuthTYPE =DotNetOpenAuth.Configuration.DotNetOpenAuthSection,DotNetOpenAuth>
      <节名称=OpenID的TYPE =DotNetOpenAuth.Configuration.OpenIdElement,DotNetOpenAuthrequirePermission =假allowLocation =真/>
      <节名称=OAuth的TYPE =DotNetOpenAuth.Configuration.OAuthElement,DotNetOpenAuthrequirePermission =假allowLocation =真/>
      <节名称=消息型=DotNetOpenAuth.Configuration.MessagingElement,DotNetOpenAuthrequirePermission =假allowLocation =真/>
      <节名称=报告TYPE =DotNetOpenAuth.Configuration.ReportingElement,DotNetOpenAuthrequirePermission =假allowLocation =真/>
    < / sectionGroup>
  < / configSections>
  < log4net的>
    <附加目的地名称=RollingFileAppender进行式=log4net.Appender.RollingFileAppender>
      <文件值=DotNetOpenAuth.log/>
      < appendToFile值=真/>
      < rollingStyle值=大小/>
      < maxSizeRollBackups值=10/>
      < maximumFileSize值=100KB/>
      < staticLogFileName值=真/>
      <布局类型=log4net.Layout.PatternLayout>
        < conversionPattern值=%DATE(GMT%日期{%Z})[%线程]%-5level%记录仪 - %消息%换行/>
      < /布局>
    < /附加器>
    <附加目的地名称=TracePageAppender型=&GTOpenIdProviderWebForms code.TracePageAppender,OpenIdProviderWebForms。
      <布局类型=log4net.Layout.PatternLayout>
        < conversionPattern值=%DATE(GMT%日期{%Z})[%线程]%-5level%记录仪 - %消息%换行/>
      < /布局>
    < /附加器>
    <! - 设置根类别,添加附加目的地,并设置默认级别 - >
    <根>
      <电平值=ALL/>
      <附加目的地-REF REF =RollingFileAppender进行/>
      <附加目的地-REF REF =TracePageAppender/>
    < /根>
    <! - 指定的级别对一些特定类别 - >
    <记录器名称=DotNetOpenAuth>
      <电平值=ALL/>
    < /记录器>
  < / log4net的>
  < dotNetOpenAuth>
    <! - 这是一个可选配置部分,在那里dotnetopenauth的方面都可以定制。 - >
    <! - 一套完整的配置选项见http://www.dotnetopenauth.net/developers/$c$c-snippets/configuration-options/  - >
    <! - <通信时钟相位差=0时十分00秒终身=0时03分零零秒严=真正的>  - >
    <! - <消息>
      &所述; untrustedWebRequest超时=0点00分30秒readWriteTimeout =00:00:01.500maximumBytesToRead =1048576maximumRedirections =10>
        < whitelistHosts>
           - >
    <! - 取消注释,以实现与本地主机通信(一般不应在生产中激活!) - >
    <! - 
          <添加名称=本地主机/>
        < / whitelistHosts>
      < / untrustedWebRequest>
    < /消息>  - >
    <! - 允许DotNetOpenAuth发布使用情况统计信息库作者以提高图书馆。 - >
    <报告启用=FALSE/>
  < / dotNetOpenAuth>
  <的appSettings>
    <! - <添加键=log4net.Internal.Debug值=真/>  - >
  < /的appSettings>
  <运行>
  < /运行>
  <启动>
    < supportedRuntime版本=4.0版的SKU =NETFramework,版本= V4.0/>
  < /启动>
< /结构>
 

解决方案

以下code,从我原来的问题修正,基于在所提供的伊恩·弗雷泽的例子:

https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ

他的code解决的三个问题:

  1. 在它看来好像AnalyticsService.Scopes.AnalyticsReadonly不工作,至少对我或我做的方式。
  2. 出于某种原因,ServiceAccountUser必须分配给AssertionFlowClient实例的ServiceAccountId属性。
  3. OAuth2Authenticator规定,我一直在寻找的IAuthenticator。

在你的项目中,包括提及:

  • 在库\ DotNetOpenAuth.dll
  • 在库\ Google.Apis.dll
  • 在库\ Google.Apis.Authentication.OAuth2.dll
  • 服务\ AnalyticsService \ Google.Apis.Analytics.v3.dll

-

 命名空间GoogleAnalyticsAPITest.Console
{
    使用System.Security.Cryptography.X509Certificates;
    使用Google.Apis.Analytics.v3;
    使用Google.Apis.Analytics.v3.Data;
    使用Google.Apis.Authentication.OAuth2;
    使用Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    使用Google.Apis.Util;

    类节目
    {
        静态无效的主要(字串[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            常量字符串ServiceAccountId =nnnnnnnnnnn.apps.googleusercontent.com;
            常量字符串ServiceAccountUser =nnnnnnnnnnn@developer.gserviceaccount.com;
            AssertionFlowClient客户端=新AssertionFlowClient(
                GoogleAuthenticationServer.Description,新X509Certificate2(@价值privatekey.p12,notasecret,X509KeyStorageFlags.Exportable))
            {
                范围= AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()
                ServiceAccountId = ServiceAccountUser //错误,为什么ServiceAccountUser已经被分配到ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator< AssertionFlowClient>身份验证=新OAuth2Authenticator< AssertionFlowClient>(客户端,AssertionFlowClient.GetState);
            AnalyticsService服务=新AnalyticsService(验证);
            字符串配置文件ID =GA:64968920;
            字符串的startDate =2010-10-01;
            字符串结束日期=2010-10-31;
            字符串指标=GA:访问;
            DataResource.GaResource.GetRequest请求= service.Data.Ga.Get(配置文件ID,的startDate,结束日期,指标);
            request.Dimensions =GA:日期;
            GaData数据= request.Fetch();
        }

    }
}
 

I realized this question has been previously asked but with little in the way of example code, so I am asking again but with at least a little bit of direction.

After hours of searching, I have come up with the following partial implementation.

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using DotNetOpenAuth.OAuth2;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            string Scope = Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
            string scopeUrl = "https://www.googleapis.com/auth/" + Scope;
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "nnnnnnnnnnn@developer.gserviceaccount.com";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"7039572692013fc5deada350904f55bad2588a2a-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = scopeUrl,
                ServiceAccountId = ServiceAccountId//,ServiceAccountUser = ServiceAccountUser
            };
            IAuthorizationState state = AssertionFlowClient.GetState(client);
            AnalyticsService service = new AnalyticsService(authenticator);
            string profileId = "ga:xxxxxxxx";
            string startDate = "2010-10-01";
            string endDate = "2010-10-18";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();
        }
    }
}

I have a couple issues. The call to AssertionFlowClient.GetState(client) results in a "invalid_scope" response as seen in the DotNetOpenAuth log of

2012-10-19 13:27:36,272 (GMT-4) [8] INFO DotNetOpenAuth - DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official) 2012-10-19 13:27:36,284 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - Preparing to send AssertionFlowMessage (2.0) message. 2012-10-19 13:27:36,294 (GMT-4) [8] INFO DotNetOpenAuth.Messaging.Channel - Prepared outgoing AssertionFlowMessage (2.0) message for https://accounts.google.com/o/oauth2/token: grant_type: assertion assertion_type: http://oauth.net/grant_type/jwt/1.0/bearer assertion: (a bunch of encoded characters go here)

2012-10-19 13:27:36,296 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - Sending AssertionFlowMessage request. 2012-10-19 13:27:36,830 (GMT-4) [8] DEBUG DotNetOpenAuth.Http - HTTP POST https://accounts.google.com/o/oauth2/token 2012-10-19 13:27:36,954 (GMT-4) [8] ERROR DotNetOpenAuth.Http - WebException from https://accounts.google.com/o/oauth2/token: { "error" : "invalid_scope" }

I have tried specifying one or both of ServiceAccountId and ServiceAccountUser with no luck.

Second, even if I get an IAuthorizationState, I am not sure how I get an IAuthenticator that can be passed to the AnalyticsService constructor.

The following is the web.config I use to enable DotNetOpenAuth logging.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, publicKeyToken=1b44e1d426115821" />
    <!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/>-->
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth">
      <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
    </sectionGroup>
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="DotNetOpenAuth.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="100KB"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <appender name="TracePageAppender" type="OpenIdProviderWebForms.Code.TracePageAppender, OpenIdProviderWebForms">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="TracePageAppender"/>
    </root>
    <!-- Specify the level for some specific categories -->
    <logger name="DotNetOpenAuth">
      <level value="ALL"/>
    </logger>
  </log4net>
  <dotNetOpenAuth>
    <!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
    <!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
    <!--<messaging clockSkew="00:10:00" lifetime="00:03:00" strict="true">-->
    <!--<messaging>
      <untrustedWebRequest timeout="00:00:30" readWriteTimeout="00:00:01.500" maximumBytesToRead="1048576" maximumRedirections="10">
        <whitelistHosts>
          -->
    <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
    <!--
          <add name="localhost"/>            
        </whitelistHosts>
      </untrustedWebRequest>
    </messaging>-->
    <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
    <reporting enabled="false"/>
  </dotNetOpenAuth>
  <appSettings>
    <!--<add key="log4net.Internal.Debug" value="true" />-->
  </appSettings>
  <runtime>
  </runtime>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

解决方案

The following code, corrected from my original question, is based on the example provided by Ian Fraser at:

https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ

His code addressed three issues:

  1. It appears as though AnalyticsService.Scopes.AnalyticsReadonly does not work, at least not for me or the way I am doing it.
  2. For some reason, the ServiceAccountUser must be assigned to the ServiceAccountId property of the AssertionFlowClient instance.
  3. OAuth2Authenticator provides the IAuthenticator that I was looking for.

In your project, include references to:

  • Lib\DotNetOpenAuth.dll
  • Lib\Google.Apis.dll
  • Lib\Google.Apis.Authentication.OAuth2.dll
  • Services\AnalyticsService\Google.Apis.Analytics.v3.dll

-

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    using Google.Apis.Util;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();            
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "nnnnnnnnnnn@developer.gserviceaccount.com";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);            
            AnalyticsService service = new AnalyticsService(authenticator);            
            string profileId = "ga:64968920";
            string startDate = "2010-10-01";
            string endDate = "2010-10-31";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();            
        }

    }
}

这篇关于如何使用服务帐户来访问谷歌Analytics API V3使用.NET C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆