Search code examples
google-cloud-datastore

Authenticating Google Cloud Datastore c# SDK


I am trying to authenticate Google Datastore c# SDK in a k8 pod running in google cloud. I could not find any way to inject the account.json file in to DatastoreDb or DatastoreClient beside using GOOGLE_APPLICATION_CREDENTIALS environment variable. Using GOOGLE_APPLICATION_CREDENTIALS environment variable is problematic since i do not want to leave the account file exposed.

According to the documentations in: https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.Datastore.V1/index.html

When running on Google Cloud Platform, no action needs to be taken to authenticate.

But that does not seem to work.

A push in the right direction will be appreciated (:


Solution

  • This is how it can be done:

        var credential = 
     GoogleCredential.FromFile(@"/path/to/google.credentials.json").CreateScoped(DatastoreClient.DefaultScopes);
        var channel = new Grpc.Core.Channel(DatastoreClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
    
        DatastoreClient client = DatastoreClient.Create(channel, settings: 
        DatastoreSettings.GetDefault());
        DatastoreDb db = DatastoreDb.Create(YOUR_PROJECT_ID, client:client);
        // Do Datastore stuff...
        // Shutdown the channel when it is no longer required.
        await channel.ShutdownAsync();

    Taken from: https://github.com/googleapis/google-cloud-dotnet/blob/master/apis/Google.Cloud.Datastore.V1/Google.Cloud.Datastore.V1/DatastoreClient.cs