Wednesday, July 27, 2016

How do you authenticate a .NET application when calling a Google API?

Much has been written, but it’s still confusing.  Today, I'll talk about how to authenticate as yourself, not on behalf of your user.

It all depends on where you want to run you .NET app.

First, write code like this to create your service:

            var credentials = Google.Apis.Auth.OAuth2.GoogleCredential
            if (credentials.IsCreateScopedRequired)
                credentials = credentials.CreateScoped(new[] {
            // Create our connection to datastore.
            _datastore = new DatastoreService(new Google.Apis.Services
                HttpClientInitializer = credentials,

Then, ask yourself, where do I want to run the code?

I want to run it on my development machine.

That’s easy. Run gcloud auth login and enter your Google credentials.

I want to run it on a Google Compute Engine instance.

When you create your app engine instance, give it access to the APIs you need:

I want to run it on a production machine in our corporate network.

  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create service account.
  3. In the Create service account window, type a name for the service account.  The name isn't important; it's for your book keeping purposes only. Select Furnish a new private key.  Then click Create.
Your new public/private key pair is generated and downloaded to your machine.  Obviously, this file enables anyone to authenticate as you, so don't share it with anyone, and keep it secure.
 Copy the .json file you just downloaded to your production machine.
Then, On the production machine, set the global environment variable GOOGLE_APPLICATION_CREDENTIALS to the path to this file.

I hope this helps.  If you have more questions about auth, please write them in the comments.

1 comment:

  1. Great post. The only thing is that "gcloud auth login" only works for *some* APIs (datastore happens to be one of them).

    Downloading a service account key file ("my-project-xxxxx.json" file) is fine for development, too.