Сбой аутентификации при смене сцены - PullRequest
2 голосов
/ 01 апреля 2019

Я установил свою аутентификацию на базе 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

Ответы [ 2 ]

2 голосов
/ 01 апреля 2019

Я много пробовал, но не получаю нужного поведения (о повторной авторизации / приложение не закрывается)

Даже если я меняю сцены, учетные данные остаются.

Если вы хотите изменитьучетная запись,

перезапустите приложение и затем выйдите из системы (Facebook или Google) в сцене приветствия

1 голос
/ 01 апреля 2019

Предполагая, что в первый раз он работает как положено, он звучит так: 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);
    }

    ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...