Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication with firestore for c# desktop app

I have prepared desktop application which is using firestore database and to get an access to it I have used GOOGLE_APPLICATION_CREDENTIALS. According to the documentation, I was not able to introduce rules for this type of authentication but I would like to do so. I have sent a question to support and I was informed to use REST API. And here is my question ? Is it possible to authenticate via REST API but to read and write data still use Google.Cloud.Firestore nuget ? How to do this ? Please remember that I have desktop app wrote in c# WPF. Maybe you know some other solution for my problem ?

like image 559
Przemo Avatar asked Jan 01 '23 14:01

Przemo


1 Answers

Thank you for feedback Frank, In your link I have found an answer. To authenticate to firestore from desktop app you need to do the following:

public FirestoreDb CreateFirestoreDbWithEmailAuthentication(string emailAddress, 
string password, string firebaseApiKey, string firebaseProjectId)
{
            // Create a custom authentication mechanism for Email/Password authentication
            // If the authentication is successful, we will get back the current authentication token and the refresh token
            // The authentication expires every hour, so we need to use the obtained refresh token to obtain a new authentication token as the previous one expires
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));
            var auth = authProvider.SignInWithEmailAndPasswordAsync(emailAddress, password).Result;
            var callCredentials = CallCredentials.FromInterceptor(async (context, metadata) =>
            {
                if (auth.IsExpired()) auth = await auth.GetFreshAuthAsync();
                if (string.IsNullOrEmpty(auth.FirebaseToken)) return;

                metadata.Clear();
                metadata.Add("authorization", $"Bearer {auth.FirebaseToken}");
            });
            var credentials = ChannelCredentials.Create(new SslCredentials(), callCredentials);

            // Create a custom Firestore Client using custom credentials
            var grpcChannel = new Channel("firestore.googleapis.com", credentials);
            var grcpClient = new Firestore.FirestoreClient(grpcChannel);
            var firestoreClient = new FirestoreClientImpl(grcpClient, FirestoreSettings.GetDefault());

            return FirestoreDb.Create(firebaseProjectId, null, firestoreClient);
}

Of course firstly you need to add email user in firestore console.

like image 178
Przemo Avatar answered Jan 13 '23 01:01

Przemo