16

I'm trying to implement Firebase Authentication system in my Unity Game Project. Everything is setup properly on the console panel on the website. I've read the docs and can't find a way to login into Google using any api within Firebase within Unity. So I bought Prime31's Play GameServices Plugin for Unity.

Here are my questions:

  1. How to authenticate using Google right within Firebase? Do I need to manage the google sign in myself?

  2. In the Firebase docs I did find:

"After a user successfully signs in, exchange the access token for a Firebase credential, and authenticate with Firebase using the Firebase credential:"

Firebase.Auth.Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(googleIdToken, googleAccessToken); auth.SignInWithCredentialAsync(credential).ContinueWith(task => { //......// });

How can I get the googleIdToken, googleAccessToken which are being passed as parameters above?

Please help (with code). I really like Firebase and would like to make it work without any third party plugins like PRIME31.

KENdi
  • 7,576
  • 2
  • 16
  • 31
ItisShikhar
  • 192
  • 1
  • 3
  • 12
  • https://stackoverflow.com/questions/40838154/retrieve-google-access-token-after-authenticated-using-firebase-authentication – vovkas Jul 03 '17 at 14:42
  • Step by step instruction help me https://stackoverflow.com/a/40946219/1043331 – vovkas Jul 03 '17 at 14:46
  • See [this answer](https://stackoverflow.com/questions/34639015/how-do-you-integrate-the-new-google-sign-in-on-a-xamarin-android-app?answertab=active#tab-top) by @SushiHangover – Masciuniria Jan 26 '18 at 01:59

5 Answers5

7

Here is the entirety of my Google SignIn code w/ Firebase Authentication and GoogleSignIn libraries:

private void SignInWithGoogle(bool linkWithCurrentAnonUser)
   {
      GoogleSignIn.Configuration = new GoogleSignInConfiguration
      {
         RequestIdToken = true,
         // Copy this value from the google-service.json file.
         // oauth_client with type == 3
         WebClientId = "[YOUR API CLIENT ID HERE].apps.googleusercontent.com"
      };

      Task<GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();

      TaskCompletionSource<FirebaseUser> signInCompleted = new TaskCompletionSource<FirebaseUser>();
      signIn.ContinueWith(task =>
      {
         if (task.IsCanceled)
         {
            signInCompleted.SetCanceled();
         }
         else if (task.IsFaulted)
         {
            signInCompleted.SetException(task.Exception);
         }
         else
         {
            Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(((Task<GoogleSignInUser>)task).Result.IdToken, null);
            if (linkWithCurrentAnonUser)
            {
               mAuth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
            }
            else
            {
               SignInWithCredential(credential);
            }
         }
      });
   }

The parameter is for signing in with intentions of linking the new google account with an anonymous user that is currently logged on. You can ignore those parts of the method if desired. Also note all of this is called after proper initialization of the Firebase Auth libraries.

I used the following libraries for GoogleSignIn: https://github.com/googlesamples/google-signin-unity

The readme page from that link will take you through step-by-step instructions for getting this setup for your environment. After following those and using the code above, I have this working on both android and iOS.

Here is the SignInWithCredential method used in the code above:

private void SignInWithCredential(Credential credential)
   {
      if (mAuth != null)
      {
         mAuth.SignInWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
      }
   }

mAuth is a reference to FirebaseAuth:

mAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Matthew Coats
  • 121
  • 1
  • 3
  • 1
    Hi Matthew, your code is missing "HandleLoginResult" reference. Please should you post the entire code? – WizardingStudios May 16 '20 at 15:45
  • Hey @Matthew, so it's been over a year now and I'm curious if this still works for you. I'm trying to do the same thing, but can't get either Android or iOS to run on my editor. Does this only work for builds and not via Unity editor? Android error is `Exception: Field currentActivity or type signature not found`, while iOS error is `EntryPointNotFoundException: GoogleSignIn_Create`. – Molasses Feb 28 '21 at 15:43
  • I can't edit my comment above, so I'm adding this comment for anyone else curious. This only works on builds (AFAIK), not in Unity editor. I've been only able to get it to run via on an actual device. – Molasses Mar 14 '21 at 13:55
  • To avoid error: "DefaultInstance already created. Cannot change configuration after creation.", add **if (GoogleSignIn.Configuration == null)** before the line for creating a new GoogleSignInConfiguration. This will prevent the error if a user cancels the google pop up to choose account and then retries it. – Kalib Crone Apr 11 '22 at 21:51
  • @Matthew what is HandleLoginResult? – Aitor Ramos Pajares Jul 28 '22 at 21:45
1

The simple answer is that there's no way in the Firebase SDK plugin for Unity to do the entirety of Google's authentication in a Unity app. I would recommend following the instructions for email/password sign on to start out. https://firebase.google.com/docs/auth/unity/start

If you really want Google sign on (which you probably do for a shipping title), this sample should walk you through it: https://github.com/googlesamples/google-signin-unity

The key is to get the id token from Google (which is a separate step from the Firebase plugin), then pass that in.

I hope that helps (even if it wasn't timely)!

Patrick Martin
  • 2,993
  • 1
  • 13
  • 11
0

For someone asking for HandleLoginResult from @Mathew Coats, here is the function used to handle after.

private void HandleLoginResult(Task<FirebaseUser> task)
        {
            if (task.IsCanceled)
            {
                UnityEngine.Debug.LogError("SignInWithCredentialAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                UnityEngine.Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception.InnerException.Message);
                return;
            }
            else
            {

                FirebaseUser newUser = task.Result;
                UnityEngine.Debug.Log($"User signed in successfully: {newUser.DisplayName} ({newUser.UserId})");
            }
        }
-2

As first, you need use Google Sign in Unity plugin to login with Google, and then, when you logged, get token and continues with Firebase Auth. Also you can try this asset http://u3d.as/JR6

tungnguyen
  • 29
  • 5
-3

Here is the code to get access token from firebase after authentication is done

 FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
            mUser.getToken(true)
                    .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
                        @Override
                        public void onComplete(@NonNull Task<GetTokenResult> task) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            if (task.isSuccessful()) {
                                String idToken = task.getResult().getToken();
                                Log.i(getClass().getName(), "got access token :" + idToken);
                            } else {
                              // show logs
                            }
                        }
                    });
Pratibha sarve
  • 369
  • 2
  • 11