gpt4 book ai didi

c# - Unity/Firebase 如何使用 Google 进行身份验证?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:04 26 4
gpt4 key购买 nike

我正在尝试在我的 Unity 游戏项目中实现 Firebase 身份验证系统。一切都在网站的控制台面板上正确设置。我已经阅读了文档,但找不到在 Unity 中使用 Firebase 中的任何 api 登录 Google 的方法。所以我购买了 Prime31 的 Play GameServices Plugin for Unity。

这是我的问题:

  1. 如何直接在 Firebase 中使用 Google 进行身份验证?我需要自己管理 Google 登录吗?

  2. 在 Firebase 文档中我确实找到了:

“用户成功登录后,将访问 token 交换为 Firebase 凭据,并使用 Firebase 凭据向 Firebase 进行身份验证:”

Firebase.Auth.Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(googleIdToken, googleAccessToken);
auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
//……//
});

如何获取上面作为参数传递的 googleIdToken、googleAccessToken?

请帮忙(用代码)。我真的很喜欢 Firebase,并希望它在没有任何第三方插件(如 PRIME31)的情况下工作。

最佳答案

这是我的完整 Google 登录代码,带有 Firebase 身份验证和 GoogleSignIn 库:

private void SignInWithGoogle(bool linkWithCurrentAnonUser)
{
GoogleSignIn.Configuration = new GoogleSignInConfiguration
{
RequestIdToken = true,
// Copy this value from the google-service.json file.
// oauth_client with type == 3
WebClientId = "[YOUR API CLIENT ID HERE].apps.googleusercontent.com"
};

Task<GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();

TaskCompletionSource<FirebaseUser> signInCompleted = new TaskCompletionSource<FirebaseUser>();
signIn.ContinueWith(task =>
{
if (task.IsCanceled)
{
signInCompleted.SetCanceled();
}
else if (task.IsFaulted)
{
signInCompleted.SetException(task.Exception);
}
else
{
Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(((Task<GoogleSignInUser>)task).Result.IdToken, null);
if (linkWithCurrentAnonUser)
{
mAuth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
}
else
{
SignInWithCredential(credential);
}
}
});
}

该参数用于登录,目的是将新的谷歌帐户与当前登录的匿名用户相关联。如果需要,您可以忽略该方法的那些部分。另请注意,所有这些都是在 Firebase Auth 库正确初始化后调用的。

我为 GoogleSignIn 使用了以下库:https://github.com/googlesamples/google-signin-unity

该链接中的自述文件页面将引导您完成为您的环境设置此设置的分步说明。在遵循这些并使用上面的代码之后,我可以在 Android 和 iOS 上使用它。

这是上面代码中使用的SignInWithCredential方法:

private void SignInWithCredential(Credential credential)
{
if (mAuth != null)
{
mAuth.SignInWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
}
}

mAuth 是对 FirebaseAuth 的引用:

mAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;

关于c# - Unity/Firebase 如何使用 Google 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43731007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com