【问题标题】:How to retrieve Google Service Account Access Token .NET如何检索 Google 服务帐户访问令牌 .NET
【发布时间】:2016-10-09 05:00:05
【问题描述】:

我需要检索 Google 服务帐户的访问令牌,然后我将使用该令牌从 Google Analytics(分析)中获取结果。我已经在 PHP 中做过,但我在 .NET 中苦苦挣扎,我使用了来自 Google Docs 的示例,但我遇到了一些问题。这是代码:

        private static String ACTIVITY_ID = "1111111";

        public static void Test()
        {
            Console.WriteLine("Plus API - Service Account");
            Console.WriteLine("==========================");

            String serviceAccountEmail = "*@developer.gserviceaccount.com";
            var certificate = new X509Certificate2(System.Web.Hosting.HostingEnvironment.MapPath("~/*.p12"), "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[] { PlusService.Scope.PlusMe }
               }.FromCertificate(certificate));

            // Create the service.

            var service = new PlusService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Plus API Sample",
            });

            Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

在线崩溃:

Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();

出现以下错误:

Google.Apis.Requests.RequestError
Not Found [404]
Errors [
    Message[Not Found] Location[ - ] Reason[notFound] Domain[global]
]

为了获得令牌,我遗漏了什么或做错了什么?另外,ACTIVITY_ID 是从 Analytics 中的视图中获取的 ID 还是其他?

【问题讨论】:

    标签: .net google-oauth service-accounts


    【解决方案1】:

    可能和this问题差不多,需要设置User属性:

    var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
                {
                    Scopes = new[] { "https://www.googleapis.com/somescope" },
                    User = "theuser@gmail.com"
                }.FromPrivateKey(cr.private_key));
    

    【讨论】:

    • 天哪,老兄......我两天来一直在寻找答案的用户部分。如果您愿意,请将其发布为我类似的 vb.net 问题的答案,我会给您奖励。
    • @SEFL 如果this 是您的问题,我认为会有所不同吗?会尽力为你解答:)
    • 这是问题所在...... User 属性确实为我解答了这个问题。
    猜你喜欢
    • 2015-04-29
    • 2019-01-05
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2016-04-29
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多