Search code examples
firebaseunity-game-enginegame-center

How to Access Auth Token in Unity with GameCenter Firebase Authentication


I would like to add the GameCenter Authentication with Firebase to my Unity Game. But in the documentation there isn't the GameCenter part (only Play Games one). I already achieved the "Unity part":

public static void GameCenterAuth()
    {
        GameCenterPlatform.ShowDefaultAchievementCompletionBanner(true);
        Social.localUser.Authenticate (GameCenterProcessAuth);
    }

    static void GameCenterProcessAuth(bool success)
    {
        if (success) 
        {
            Social.ReportProgress("Achievement01", 100, (result) => {
            Debug.Log(result ? "Reported achievement" : "Failed to report achievement");
        });

        }
        else
        {
            Debug.Log ("Failed to authenticate");
        }
    }

But it misses the link with Firebase. For this I need to get the access token of GameCenter but like the doc doesn't exist, I don't know how to achieve this.


Solution

  • Hopefully there aren't many holes in the Unity documentation, but when you do find one you can often find sample code in the Unity Quickstarts (as these are also used to validate changes to the Unity SDK).

    From UIHandler.cs in the Auth quickstart:

        public Task SignInWithGameCenterAsync() {
          var credentialTask = Firebase.Auth.GameCenterAuthProvider.GetCredentialAsync();
          var continueTask = credentialTask.ContinueWithOnMainThread(task => {
            if(!task.IsCompleted)
              return null;
    
            if(task.Exception != null)
              Debug.Log("GC Credential Task - Exception: " + task.Exception.Message);
    
            var credential = task.Result;
    
            var loginTask = auth.SignInWithCredentialAsync(credential);
            return loginTask.ContinueWithOnMainThread(HandleSignInWithUser);
          });
    
          return continueTask;
        }
    

    What's weird about GameCenter is that you don't manage the credential directly, rather you request it from GameCenter (Here's PlayGames by comparison, which you have to cache the result of Authenticate manually).

    So in your code, I'd go into the if (success) block and add:

    GameCenterAuthProvider.GetCredentialAsync().ContinueWith(task => {
        // I used ContinueWith
        // be careful, I'm on a background thread here.
        // If this is a problem, use ContinueWithOnMainThread
        if (task.Exception != null) {
            FirebaseAuth.GetInstance.SignInWithCredentialAsync(task.Result).ContinueWithOnMainThread(task => {
                // I used ContinueWithOnMainThread
                // You're on the Unity main thread here, so you can add or change scene objects
                // If you're comfortable with threading, you can change this to ContinueWith
            });
        }
    });