简体   繁体   中英

Unity/Firebase How to authenticate using Google?

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.

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;

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)!

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})");
            }
        }

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

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
                            }
                        }
                    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM