Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何重新登录到再次运行应用程序时创建的匿名帐户?_C#_Firebase_Unity3d_Firebase Authentication - Fatal编程技术网

C# 如何重新登录到再次运行应用程序时创建的匿名帐户?

C# 如何重新登录到再次运行应用程序时创建的匿名帐户?,c#,firebase,unity3d,firebase-authentication,C#,Firebase,Unity3d,Firebase Authentication,您好,我是一名新手开发人员,我有一个来宾登录问题 我创建了一个匿名帐户并关闭了应用程序 如何重新登录到再次运行应用程序时创建的匿名帐户 第一次登录时,匿名帐户的创建工作正常 当我退出并再次登录时,我加载了我保存并登录的[uid]或[idToken] 但我犯了个错误 using System.Collections; using System.Collections.Generic; using UnityEngine; using GoogleMobileAds.Api; using Fireb

您好,我是一名新手开发人员,我有一个来宾登录问题
我创建了一个匿名帐户并关闭了应用程序
如何重新登录到再次运行应用程序时创建的匿名帐户

第一次登录时,匿名帐户的创建工作正常 当我退出并再次登录时,我加载了我保存并登录的[uid]或[idToken] 但我犯了个错误

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using Firebase.Auth;
using System.Security.Cryptography;

public class GameManager : MonoBehaviour
{
    private FirebaseAuth auth;
    private FirebaseUser user;

    void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs)
    {
        if (auth.CurrentUser != user)
        {
            bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;

            if (!signedIn && user != null)            
                Debug.Log("Signed out " + user.UserId);

            user = auth.CurrentUser;

            if (signedIn)            
                Debug.Log("Signed in " + user.UserId);                

        }
    }

    public void OnClickedLogIn()
    {
        InitializeFirebase();

        if(GetString("idToken") == null)
        {
            auth.SignInAnonymouslyAsync().ContinueWith(task => {
                if (task.IsCanceled)
                {
                    Debug.LogError("SignInAnonymouslyAsync was canceled.");
                    return;
                }
                if (task.IsFaulted)
                {
                    Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
                    return;
                }

                FirebaseUser newUser = task.Result;

                Debug.LogFormat("User signed in successfully: {0} ({1})",
                    newUser.DisplayName, newUser.UserId);

                string uid = newUser.UserId;
                SetString("uid", uid, "testKey");

                //토큰저장
                task.Result.TokenAsync(true).ContinueWith(work => {
                    if (work.IsCanceled)
                    {
                        Debug.LogError("TokenAsync was canceled.");
                        return;
                    }

                    if (work.IsFaulted)
                    {
                        Debug.LogError("TokenAsync encountered an error: " + task.Exception);
                        return;
                    }

                    string idToken = work.Result;                    
                    Debug.Log(task.Result.UserId + "\n" + idToken);                    
                    SetString("idToken", idToken, "testKey");
                });
            });
        }
        else
        {
            Debug.Log("기존로그인");
            string uid = GetString("uid");  **uid & token **
            Debug.Log(uid);
            string token = GetString("idToken");
            Debug.Log(token);           

            auth.SignInWithCustomTokenAsync(token).ContinueWith(task =>
            {
                if (task.IsCanceled)
                {
                    Debug.LogError("IsCanceled");
                    return;
                }
                if (task.IsFaulted) **<<<-------------- this error occured**
                {
                    Debug.LogError("IsFaulted" + task.Exception);
                    return;
                }
                auth.StateChanged += AuthStateChanged;
                AuthStateChanged(this, null);
                Debug.Log("로그인성공" + user.UserId);
            });
        }
    }

    public void OnClickedDelete()
    {
        PlayerPrefs.DeleteAll();
    }

    public static void SetString(string _key, string _value, string _encryptKey)
    {
        //key 숨기기
        MD5 md5Hash = MD5.Create();
        byte[] hashData = md5Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_key));
        string hashKey = System.Text.Encoding.UTF8.GetString(hashData);

        byte[] secret = md5Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_encryptKey));
        //암호값 바이트 배열에넣기
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(_value);
        //값 암호화 3des
        TripleDES des = new TripleDESCryptoServiceProvider();
        des.Key = secret;
        des.Mode = CipherMode.ECB;
        ICryptoTransform xform = des.CreateEncryptor();
        byte[] encrypted = xform.TransformFinalBlock(bytes, 0, bytes.Length);
        //암호화배열 변환 읽을수있는문자열로
        string encryptedString = System.Convert.ToBase64String(encrypted);
        //값넣기
        PlayerPrefs.SetString(hashKey, encryptedString);
    }

    public static string GetString(string _key, string _encryptKey = "testKey")
    {
        //key문자열 숨기기
        MD5 md5Hash = MD5.Create();
        byte[] hashData = md5Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_key));
        string hashKey = System.Text.Encoding.UTF8.GetString(hashData);

        byte[] secret = md5Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_encryptKey));

        if (!PlayerPrefs.HasKey(hashKey))
            return null;

        //암호화된값 검색 및 Base64로 디코드
        string value = PlayerPrefs.GetString(hashKey);
        byte[] bytes = System.Convert.FromBase64String(value);

        //암호화된 값 3des로
        TripleDES des = new TripleDESCryptoServiceProvider();
        des.Key = secret;
        des.Mode = CipherMode.ECB;
        ICryptoTransform xform = des.CreateDecryptor();
        byte[] decrypted = xform.TransformFinalBlock(bytes, 0, bytes.Length);

        //암호해제 값 적절한문자열로
        string decryptedString = System.Text.Encoding.UTF8.GetString(decrypted);

        return decryptedString;
    }
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
使用GoogleMobileAds.Api;
使用Firebase.Auth;
使用System.Security.Cryptography;
公共类GameManager:MonoBehavior
{
私有FirebaseAuth-auth;
私有FirebaseUser用户;
void initializefrebase()
{
auth=FirebaseAuth.DefaultInstance;
auth.StateChanged+=AuthStateChanged;
AuthStateChanged(此,空);
}
void AuthStateChanged(对象发送方,System.EventArgs EventArgs)
{
if(auth.CurrentUser!=用户)
{
bool signedIn=user!=auth.CurrentUser&&auth.CurrentUser!=null;
如果(!signedIn&&user!=null)
Debug.Log(“注销”+user.UserId);
user=auth.CurrentUser;
如果(签名)
Debug.Log(“登录”+user.UserId);
}
}
public void OnClickedLogIn()
{
初始化REBASE();
if(GetString(“idToken”)==null)
{
auth.signinanoymouslyasync().ContinueWith(任务=>{
如果(task.IsCanceled)
{
LogError(“signinanomyouslyasync已取消”);
返回;
}
if(task.IsFaulted)
{
LogError(“SigninanoymouslyAsync遇到错误:“+task.Exception”);
返回;
}
FirebaseUser newUser=task.Result;
LogFormat(“用户成功登录:{0}({1})”,
newUser.DisplayName,newUser.UserId);
字符串uid=newUser.UserId;
设置字符串(“uid”,uid,testKey”);
//토큰저장
task.Result.TokenAsync(true).ContinueWith(work=>{
如果(工作被取消)
{
LogError(“TokenAsync被取消”);
返回;
}
if(work.IsFaulted)
{
LogError(“TokenAsync遇到错误:“+task.Exception”);
返回;
}
字符串idToken=work.Result;
Debug.Log(task.Result.UserId+“\n”+idToken);
SetString(“idToken”,idToken,testKey”);
});
});
}
其他的
{
调试日志(“기존로그인");
字符串uid=GetString(“uid”);**uid和令牌**
调试日志(uid);
string token=GetString(“idToken”);
Debug.Log(令牌);
auth.SignInWithCustomTokenAsync(令牌).ContinueWith(任务=>
{
如果(task.IsCanceled)
{
Debug.LogError(“已取消”);
返回;
}

如果(task.IsFaulted)**在重新启动应用程序后,应自动提取用户以前的身份。您的
AuthStateChanged
应使用非空用户自动激发。

重新启动应用程序后,用户为空。……我已初始化了eFrabase()嗯……也许Unity SDK不会自动持久化令牌。如果您只是自动调用
auth.signinanoymouslyasync()
,它是否会生成相同的UID(其他Firebase SDK就是这样做的)?不,会创建一个新帐户。不同的uidHmmm……在这种情况下,我不知道。大多数(但不是全部)Firebase SDK保留身份验证信息。非常感谢您的帮助