How to retrieve Google Service Account Access Token .NET

走远了吗. 提交于 2019-12-08 13:34:36

问题


I need to retrieve an access token for a Google service account, then I'll use the token to get the results from Google Analytics. I've already did it in PHP but I'm struggling with .NET, I've used an example from the Google Docs but i'm having some issues. This is the code:

        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();
        }
    }
}

It crashes on the line:

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

With the following error:

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

What am I missing or doing wrong in order to get the Token? and also, is the ACTIVITY_ID the ID taken from the View in Analytics or something else?


回答1:


It might be about the same as this issue, you need to set the User property:

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));


来源:https://stackoverflow.com/questions/36478267/how-to-retrieve-google-service-account-access-token-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!