使用 firestore 为 c# 桌面应用程序进行身份验证

Authentication with firestore for c# desktop app

我准备了使用 firestore 数据库的桌面应用程序,为了访问它,我使用了 GOOGLE_APPLICATION_CREDENTIALS。根据文档,我无法为这种类型的身份验证引入规则,但我想这样做。我已向支持人员发送问题,并被告知使用 REST API。这是我的问题?是否可以通过 REST API 进行身份验证,但仍使用 Google.Cloud.Firestore nuget 读取和写入数据?这该怎么做 ?请记住,我有用 c# WPF 编写的桌面应用程序。也许您知道我的问题的其他解决方案?

Github repo for the google-cloud-dotnet libraries 来看,他们似乎总是使用 GOOGLE_APPLICATION_CREDENTIALS 访问 Firestore。

在这种情况下,无法像使用 Firebase 身份验证凭据那样使用该库。这些issues on the repo似乎也指向那个方向。

要使用 Firebase 身份验证凭据访问 Firestore,在这种情况下,您必须通过 REST API 访问它。

感谢您的反馈,弗兰克,在您的 link 中我找到了答案。要从桌面应用程序向 Firestore 进行身份验证,您需要执行以下操作:

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);
}

当然首先你需要在firestore控制台添加邮箱用户。