8
votes

So far all the examples of using Google Cloud Firestore with .net show that you connect to your Firestore db by using this command:

FirestoreDb db = FirestoreDb.Create(projectId);

But is this skipping the step of authentication? I can't seem to find an example of wiring it up to use a Google service account. I'm guessing you need to connect using the service account's private_key/private_key_id/client_email?

4
It looks like you might create a GOOGLE_APPLICATION_CREDENTIALS environment variable and then set the contents of the service account credentials json file to that variable per this documentation, I'm giving that a try now.mkimmet

4 Answers

12
votes

You can also use the credentials stored in a json file:

    GoogleCredential cred = GoogleCredential.FromFile("credentials.json");
    Channel channel = new Channel(FirestoreClient.DefaultEndpoint.Host,
                  FirestoreClient.DefaultEndpoint.Port,
                  cred.ToChannelCredentials());
    FirestoreClient client = FirestoreClient.Create(channel);
    FirestoreDb db = FirestoreDb.Create("my-project", client);
10
votes

I could not compile @Michael Bleterman's code, however the following worked for me:

using Google.Cloud.Firestore;
using Google.Cloud.Firestore.V1;


var jsonString = File.ReadAllText(_keyFilepath);
var builder = new FirestoreClientBuilder {JsonCredentials = jsonString};
FirestoreDb db = FirestoreDb.Create(_projectId, builder.Build());

Packages I use:

<PackageReference Include="Google.Cloud.Firestore" Version="2.0.0-beta02" />
<PackageReference Include="Google.Cloud.Storage.V1" Version="2.5.0" />
6
votes

But is this skipping the step of authentication?

No. It will use the default application credentials. If you're running on Google Cloud Platform (AppEngine, GCE or GKE), they will just be the default service account credentials for the instance. Otherwise, you should set the GOOGLE_APPLICATION_CREDENTIALS environment variable to refer to a service account credential file.

From the home page of the user guide you referred to:

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

Otherwise, the simplest way of authenticating your API calls is to download a service account JSON file then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to refer to it. The credentials will automatically be used to authenticate. See the Getting Started With Authentication guide for more details.

It's somewhat more awkward to use non-default credentials; this recent issue gives an example.

3
votes

This worked for me.

https://pieterdlinde.medium.com/netcore-and-cloud-firestore-94628943eb3c

string filepath = "/Users/user/Downloads/user-a4166-firebase-adminsdk-ivk8q-d072fdf334.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", filepath);
fireStoreDb = FirestoreDb.Create("user-a4166");