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
                .GetApplicationDefaultAsync().Result;
            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[] {
                    DatastoreService.Scope.Datastore,
                    DatastoreService.Scope.UserinfoEmail,
                });
            }
            // Create our connection to datastore.
            _datastore = new DatastoreService(new Google.Apis.Services
                .BaseClientService.Initializer()
            {
                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.

Monday, May 2, 2016

Yes, you can run your ASP.NET application on Google's cloud.

For the past 3 months, my team was busy working on the samples and documentation that show an ASP.NET application running on Google Cloud Platform.  Now, they are ready to share with you!

https://cloud.google.com/dotnet/getting-started/hello-world shows you how to deploy an ASP.NET application to an instance running on Google Compute Engine.

https://cloud.google.com/dotnet/getting-started/tutorial-app shows you how to get the most out of the Google Cloud Platform:

  • Use Entity Framework and Google Cloud SQL to store data.
  • Use Datastore to store data.
  • Store big blobs of data in Google Cloud Storage.
  • Execute long-running processes in background processes with Google Pub/Sub.
Give it a try, and let me know what you think!