我设置了我的Firebase身份验证,并且效果很好。但是,当我加载其他场景并返回欢迎场景时,身份验证失败。场景变化时我应该怎么做才能重新认证或保持登录状态?
“我的验证码”以供认证:
public void Start()
{
InitializeFirebase();
InitializePlayGamesPlatform();
SignInPlayGames();
}
public void InitializeFirebase()
{
Debug.Log("UserManager: Setting up Firebase Auth");
auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.StateChanged += AuthStateChanged;
auth.IdTokenChanged += IdTokenChanged;
// Specify valid options to construct a secondary authentication object.
if (otherAuthOptions != null &&
!(String.IsNullOrEmpty(otherAuthOptions.ApiKey) ||
String.IsNullOrEmpty(otherAuthOptions.AppId) ||
String.IsNullOrEmpty(otherAuthOptions.ProjectId)))
{
try
{
otherAuth = Firebase.Auth.FirebaseAuth.GetAuth(Firebase.FirebaseApp.Create(
otherAuthOptions, "Secondary"));
otherAuth.StateChanged += AuthStateChanged;
otherAuth.IdTokenChanged += IdTokenChanged;
}
catch (Exception)
{
Debug.Log("UserManager: ERROR: Failed to initialize secondary authentication object.");
}
}
AuthStateChanged(this, null);
}
public void InitializePlayGamesPlatform()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.RequestServerAuthCode(false)
.Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
auth = FirebaseAuth.DefaultInstance;
}
public void SignInPlayGames()
{
connecting = true;
ServerConnectionStatus.GetComponent<Text>().text = "Connecting to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.black;
Social.localUser.Authenticate((bool success) => {
if (!success)
{
Debug.LogError("UserManager: Failed to Sign in into PlayGames Service");
ServerConnectionStatus.GetComponent<Text>().text = "Cannot Connect to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.red;
connecting = false;
return;
}
AuthCode = PlayGamesPlatform.Instance.GetServerAuthCode();
if (string.IsNullOrEmpty(AuthCode))
{
Debug.LogError("UserManager: Signed in into PlayGames Service, Failed to get Server Auth Code");
ServerConnectionStatus.GetComponent<Text>().text = "Cannot Connect to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.red;
connecting = false;
return;
}
Debug.LogFormat("UserManager: Server Auth Code = {0}", AuthCode);
Credential credential = PlayGamesAuthProvider.GetCredential(AuthCode);
auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
if (task.IsCanceled)
{
Debug.LogError("UserManager: SignInWithCredentialAsync was canceled.");
ServerConnectionStatus.GetComponent<Text>().text = "Cannot Sign in to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.red;
task.Exception.ToString();
connecting = false;
return;
}
if (task.IsFaulted)
{
Debug.LogError("UserManager: SignInWithCredentialAsync encountered an error: " + task.Exception);
ServerConnectionStatus.GetComponent<Text>().text = "Cannot Sign in to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.red;
connecting = false;
return;
}
user = task.Result;
Debug.LogFormat("UserManager: User signed in successfully: {0} ({1})",
user.DisplayName, user.UserId);
ServerConnectionStatus.GetComponent<Text>().text = "Connected to PlayGames";
ServerConnectionStatus.GetComponent<Text>().color = Color.green;
connected = true;
connecting = false;
nick = auth.CurrentUser.DisplayName;
SetPlayerName(nick);
});
});
}
public void SetPlayerName(string value)
{
PhotonNetwork.NickName = value;
PlayerPrefs.SetString("PlayerName", value);
}
void AuthStateChanged(object sender, System.EventArgs eventArgs)
{
Firebase.Auth.FirebaseAuth senderAuth = sender as Firebase.Auth.FirebaseAuth;
Firebase.Auth.FirebaseUser user = null;
if (senderAuth != null) userByAuth.TryGetValue(senderAuth.App.Name, out user);
if (senderAuth == auth && senderAuth.CurrentUser != user)
{
bool signedIn = user != senderAuth.CurrentUser && senderAuth.CurrentUser != null;
if (!signedIn && user != null)
{
Debug.Log("UserManager: Signed out " + user.UserId);
}
user = senderAuth.CurrentUser;
userByAuth[senderAuth.App.Name] = user;
if (signedIn)
{
Debug.Log("UserManager: Signed in " + user.UserId);
displayName = user.DisplayName ?? "";
DisplayDetailedUserInfo(user, 1);
}
}
}
结果错误:
04-01 01:37:41.330:E / Unity(6065):UserManager:SignInWithCredentialAsync遇到错误:System.AggregateException:发生一个或多个错误。
---> System.AggregateException:发生一个或多个错误。
---> Firebase.FirebaseException:提供的身份验证凭证格式错误或已过期。 [从playgames.google.com获取访问令牌时出错,OAuth2重定向uri是:http://localhost,响应:OAuth2TokenResponse {params:error = invalid_grant&error_description = Bad%20Request,httpMetadata:HttpMetadata {status = 400,cachePolicy = NO_CACHE,cacheDuration = null,cacheImmutable = false,staleWhileRevalidate = null,文件名= null,lastModified = null,标头= HTTP / 1.1 200 OK
答案 0 :(得分:2)
我尝试了很多,但没有得到想要的行为(关于重新验证/应用程序不退出)
即使我更改场景,凭据仍然保留。
如果要更改帐户,
重新启动应用程序,然后在欢迎场景中注销(facebook或google)
答案 1 :(得分:1)
假设它第一次按预期运行,听起来像DontDestroyOnLoad
就是您想要的:
切换场景时不会破坏该对象->因此不会再次运行Start
方法。但是,您还需要将其与singleton
模式结合使用,以确保返回到第一个场景时不会再次添加/运行它:
public class AuthComponent : MonoBehaviour
{
private static AuthComponent singleton;
private void Awake()
{
// Check if already another AuthComponent running
if(singleton)
{
Debug.Log("Already another AuthComponent running");
Destroy(gameObject);
return;
}
// Otherwise store a global reference of this AuthComponent
singleton = this;
// and make it DontDestroyOnLoad
DontDestroyOnLoad(gameObject);
}
...
}