*

Authentication – Google (PlayGame)

This article elaborates on the basic steps of how to authenticate end-users with their Google credentials through Google Play Game in a Unity Android app example. If you want to use OpenID Connect to authenticate end-users with their Google credential, check out the article — Authentication - Google (OpenID) for detail.

Prerequisites

  • You have a Google Play developer account
  • Your testing device with Android API level 19 and above

Step 1: Create an application on Unity editor

  • Open Unity hub and create a new project.
  • Download and import the latest brainCloud client Unity package to this project. Once imported the plugin correctly, you will find the brainCloud tab appears on the editor menu.
image.png (1052×521)
  • Download and import the latest Google Play Games plugin for Unity from repositories of Google Play Game Services. (for the time being, version is 0.10.12)
image.png (827×593)
  • Download and import the latest Google Sign-In Unity Plugin from repositories of Google Samples. We will use it to require server auth codes that will be passed to brainCloud method AuthenticateGoogle in our code example. (Note that if you see some files already exist in your project, just uncheck them. Also, in some cases, the PlayServiceResover might cause errors in your project, you can uncheck them too)

Advice

Note that this step is just used as an extra guarantee mechanism to assure your app can get ServerAuthCode from users Google login. It is ONLY necessary in the case that you cannot get ServerAuthCode from PlayGamesPlatform in certain versions of Google Play Games plugin for Unity that users reported, otherwise, totally ignore this step and its related code block

image.png (848×661)
  • After plugins installed, you should be able to find Google Play Games menu appears under Window tab, we will use it to configure Android setup later afterward a game created on Google Play Console.
image.png (852×544)
  • You should find these plugins imported folder under the asset.
image.png (898×295)
  • Open brainCloud setting from the tab, select or create a brainCloud back-end app linked to your project.
image.png (704×532)
  • Create some UI elements to invoke initialize brainCloud and Google SignIn from your script.
image.png (864×442)
  • Functions and the code that linked behind the buttons are similar to below. Once end-users login into their Google account with Google Play Games by setting UseGameSignIn as true, so we can get their userId via calling GetUserId() from success callback, and get their server auth codes from Google Sign in API, then pass them to brainCloud Google authentication method — AuthenticateGoogle
    public void RegisterDeviceToken()
    {
        GoogleSignIn.Configuration = configuration;
        GoogleSignIn.Configuration.UseGameSignIn = true;
        GoogleSignIn.DefaultInstance.SignIn().ContinueWith(GoogleSinInCallback);
    }

    public void GoogleSinInCallback(Task<GoogleSignInUser> task)
    {
        if (task.IsFaulted)
        {
            bcreturn.GetComponent<Text>().text = "Failed to call Google SignIn()";
        }
        else
        {
            serverAuthCode = task.Result.AuthCode;
        }
    }

    public void GetGoogleUserId()
    {
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        .RequestIdToken()
        .RequestServerAuthCode(false)
        .Build();

        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        Social.localUser.Authenticate((bool success) => {
            if (success)
            {
                googleId = PlayGamesPlatform.Instance.GetUserId();
                channelid.GetComponent<InputField>().text = googleId;
            }
            else
            {
                bcreturn.GetComponent<Text>().text = "Failed to get Signed in user info";
            }
        });
    }

    public void AuthenticateBC()
    {
        if (!string.IsNullOrEmpty(googleId))
        {
            _bc.AuthenticateGoogle(googleId, serverAuthCode, true, authSuccess_BCcall, authError_BCcall);
        }
        else
        {
            bcreturn.GetComponent<Text>().text = "log into your Google account first!";
        }
    }
  • Finish the rest callbacks code in your script. Check the completed code from our GitHub Google Authentication project example for reference. (Note that, GoogleSignInConfiguration requires WebClientId to represent user in order to call Googel SignIn, we will need to config this in our code after the client credential created from Google Cloud Console later.)
  • Now, click Build Settings from Unity File tab, switch platform to Android. Then, create a keystore from Keystore Manager and save it to your local if you don’t have one.
image.png (1582×643)
  • Set up your app package name as well via Player Settings.
image.png (767×680)
  • Now we can move to the next step to create a Google project.

Step 2: Create a Google project and configure it with OAuth 2.0 Client Credential

  • Before creating a project, let’s generate a SHA1 fingerprint by using the keystore and package name that we created from the previous step via the local terminal by using Java JDK keytool command keytool -exportcert -alias your-keystore-alia -keystore path-to-your-keystore-file -list -v. ( if not set this command globally, to use this keytool command you might need to cd into your java JDK home folder)
image.png (1172×616)
  • Then, instead of going to Google Cloud Console to create a project and add auth client credential manually, we can go to the android-developer Google Sign In page and create a project from there. (by utilizing this, a Google project and Android client ID for OAuth 2.0 created in just one click), paste your Android app package name and SHA1 fingerprint accordingly when asked and create the project.
image.png (611×454)
  • Now, open Google Cloud Platform, you should be able to see both project and OAuth 2.0 Client IDs created for you.
image.png (1621×489)
  • Click the main navigation menu open APIs & Services page from GCP console. Click ENABLE APIS AND SERVICES button, search Google Play Game Services and enable it, you should be able to see it listed on the dashboard after enabled. (Note that after you tested your app when completed, you will be able to see several some request traffic generated like the picture shown below).
image.png (1535×590)
  • Now, we finished the configurations for our project from GCP, note down Client ID and its secret of Web client credential, also, the project number, we will need them to configure in brainCloud console. (Note that you may already notice, the project number actually prefixed to Client ID)
image.png (852×519)

Step 3: Configure Google client credential on brainCloud

  • Open your corresponding brainCloud app from brainCloud development portal, navigate to Design | Core App Info page.
image.png (817×526)
  • Click Google under Configure Platforms and paste your Client ID and its secret of Web client credential, also the Google project number, into Google configs fields respectively.
image.png (795×451)
  • Make sure the Google Android platform is selected from the Design | Core App Info | Platforms page.
image.png (1085×556)
  • Now, we finished the settings from brainCloud, let us move to the next step to create a game in Google Play Console.

Step 4: Create a Google Play Game in Google Play Console

  • Log into your Google Play Console and create a new app.
image.png (1253×673)
  • Go to the Configuration page under Play Games Services link your GCP project to this new game by selecting the project from the cloud project dropdown menu and click Use.
image.png (1278×698)
  • After that, click Add credential, select GCP project’s OAuth client, click Save chagnges, now, you should see the Android client credential is added to this game.
image.png (1060×673)
  • The screen of Play Games Services configuration should be like below.
image.png (1165×491)
  • Go ahead to create several testers for your game (since we will not publish this game to the public, for demonstration purposes, you have to create testers to test Google sign in with their Google accounts) by selecting the Testers menu.
image.png (982×556)
  • Create one dummy game resource from any resources ( Achievements, Events, or Leaderboards) listed under Play Games Services, we will use it to set up Google Play Game connection from Unity editor, the leftover setting from step 1. (for this example, we will create an Achievements resource)
image.png (1246×735)
  • Click Get resources button from Achievements list, copy down the Android (XML)format content.
image.png (1759×454)

Step 5: Final set up for Android app in Unity and build test app

  • Go back to your Unity editor, click Android setup from the Google Play Games menu, paste the resource content from the previous step and GCP Web client ID respectively to pop-up setting window as shown following.
image.png (1151×848)
  • Referencing this Client ID as Google SignIn config in your code too.
  • Go to the Build Settings screen and build APK for your test device.
image.png (767×739)

Step 6: Test

  • Install APK which built from the previous step to your device and test it. You may be asked to install Google Play Games if it did not exist in your test Android device. Install it and login into one of your Play Game Services tester account.
image.png (948×227)
  • Grant test app permission to your test account.
image.png (942×225)
  • Log into brainCloud after successfully logged in Google account.
image.png (1047×244)
  • Check the authenticated tester user from the brainCloud console.
image.png (921×239)