Я установил свою аутентификацию на базе 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: http://localhost, ответ: OAuth2TokenResponse {params: error = invalid_grant & error_description = Bad% 20Request, httpMetadata: HttpMetadata {status = 400, cachePolicy = NO_C)= null, cacheImmutable = false, staleWhileRevalidate = null, имя файла = null, lastModified = null, заголовки = HTTP / 1.1 200 OK