LS_
LS_

Reputation: 7149

How to retrieve Google Service Account Access Token .NET

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?

Upvotes: 0

Views: 764

Answers (1)

Kapé
Kapé

Reputation: 4811

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 = "[email protected]"
            }.FromPrivateKey(cr.private_key));

Upvotes: 1

Related Questions