【问题标题】:Authentication with firestore for c# desktop app使用 c# 桌面应用程序的 firestore 进行身份验证
【发布时间】:2019-10-18 12:02:02
【问题描述】:

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

【问题讨论】:

    标签: c# google-cloud-firestore desktop-application


    【解决方案1】:

    感谢您的反馈 Frank,在您的链接中我找到了答案。要从桌面应用程序向 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控制台中添加email用户。

    【讨论】:

    • 需要 nuget 包 FirebaseAuthentication.net
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2019-10-04
      • 2011-06-24
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多