首页 > 解决方案 > Web 浏览器无法使用 .net 桌面应用程序中的 Firebase SignInWithOAuth 打开或打开一次

问题描述

我正在构建一个 C# 桌面应用程序,旨在授权使用他的谷歌帐户 (gmail) 的 firebase 用户。

问题是下面的代码不规则地打开浏览器,这意味着有时浏览器 - (包含电子邮件以便用户选择其中一个登录) - 打开,而其他时候不打开。知道虽然在某些情况下浏览器没有打开,但是调用该函数后在firebase中注册了google账号(可能是最后一次用在这个浏览器上)。

我需要在调用该函数时打开浏览器,以便用户知道他选择了哪个谷歌帐户。

这是我正在使用的主要代码:

private async void GoogleClick()
{
    try
    {
        var result = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets { ClientId = GoogleClientId },
            new[] { "email", "profile" },
            "user",
            CancellationToken.None);

        if (result.Token.IsExpired(SystemClock.Default))
        {
            await result.RefreshTokenAsync(CancellationToken.None);
        }

        this.FetchFirebaseData(result.Token.AccessToken, FirebaseAuthType.Google);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

private async void FetchFirebaseData(string accessToken, FirebaseAuthType authType)
{
    try
    {
        // Convert the access token to firebase token
        var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseAppKey));
        var data = await auth.SignInWithOAuthAsync(authType, accessToken);

        // Setup FirebaseClient to use the firebase token for data requests
        var db = new FirebaseClient(
               FirebaseAppUri,
               new FirebaseOptions
               {
                   AuthTokenAsyncFactory = () => Task.FromResult(data.FirebaseToken)
               });

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

这是我希望在用户单击“使用 Google 登录”按钮时出现的对话框: 截图

标签: c#.netfirebasegmail

解决方案


如果您想强制用户每次单击按钮时都将登录,那么有一种解决方法可能会有所帮助。您必须在每次用户想要登录时重新授权用户,使用 GoogleWebAuthorizationBroker.ReauthorizeAsync(,) 方法,以下是编辑后的代码:

    UserCredential userCredentials=null;
    private async void GoogleClick()
    {
        try
        {

            userCredentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = GoogleClientId },
                new[] { "email", "profile" },
                "user",
                CancellationToken.None);

            if (userCredentials != null)
                await GoogleWebAuthorizationBroker.ReauthorizeAsync(userCredentials, CancellationToken.None);

                     try
            {
                await userCredentials.RefreshTokenAsync(CancellationToken.None);
            }
            catch (Exception ex) { }
            //}


            this.FetchFirebaseData(userCredentials.Token.AccessToken, FirebaseAuthType.Google);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

推荐阅读