Tutorial - Authentication with Google Play Games

Information in this guide is correct from date of upload: 2023/03/07

Summary
This is a step by step authentication tutorial made to simplify the many different pages that are required to set up Google Play Games Authentication.

More information can be found here.

Requirements

Authentication integration with Google Play Games
Initial Google Play Console setup

  • Sign in to google play console
  • Create a new app. *More detailed steps can be found on the official website here
  • Fill in your app name language and if your application is free or paid
  • Choose GAME in the app details. Your application must be type GAME to access the Setup and Management Menu

  • Select Create App

  • Go to Google Play Console > Grow > Play Games Services > Setup and management > Configuration

  • Choose the appropriate Google API selection for your game eg: No, My game doesn’t use Google APIs

  • Click on he Create button

  • Select Setup and Management>Configuration>Credentials>Configure

  • Select Google Cloud Platform

  • Next continue configuring Google Cloud Platform

Google Cloud Platform Setup

  • Choose if your OAUTH consent is External or Internal.

  • Select Create

  • Fill in the **required information*

  • Select Save and continue

  • Add the following scopes: games,games_lite and drive.appdata

  • Select Update then Save and continue

  • Add test users. These should be google accounts associated with Google and Google Play Games

  • Click on Save and continue, Navigate back go the Google Play Console

Google Play Console setup continued

  • [OPTIONAL] If you previously confirmed and configured your oAuth, by following steps 1-8 in the previous section, skip ahead to step 4

  • Go to Play Games Services > Setup and management > Configuration

  • Select Configure your oAuth consent screen and confirm configuration

  • Click on Add Credential to create a credential for Android

  • Select Type Android

  • Click Create OAuth client.

  • Follow the steps proposed below

  • On Create OAuth Client ID Page - Select the Application Type Android

  • Name should match the Project Name

  • Paste your Package Name. * This can be found in the Unity Editor > Edit Project Settings > Player > Android> Other Settings > Package Name.

  • You must build your project at least once and generate a keystore before moving on to the next step. Learn more here

  • Open a Command Prompt on Windows or Terminal on a Mac

  • WINDOWS: *Required to have JDK installed

  • Generate a SHA-1 key by typing the following into your Command Prompt

  • keytool -list -keystore .android[yourkeystorename].keystore -v*

  • [If the above fails] Generate a SHA-1 by navigating to your JDK installation folder normally located under C:\Program Files\Java\jdk[version]\bin> using the Command Prompt *depending on your JDK installation

  • Copy your keystore folder path. This is normally generated when create your keystore

  • Run the following command:

  • keytool -list -keystore [keystorefolderpath][yourkeystorename].keystore -v*

  • MAC *Required to have JDK installed

  • Generate a SHA-1 key by typing the following into your Terminal

  • keytool -list -keystore ~/.android/[yourkeystorename].keystore -v*

  • [If the above fails] Generate a SHA-1 by navigating to your JDK installation folder normally located under /Library/Java/JavaVirtualMachines/jdk[VERSION] *depending on your JDK installation using the Terminal

  • Copy your keystore folder path. This is normally generated when create your keystore

  • Run the following command:

  • keytool -list -keystore [keystorefolderpath][yourkeystorename].keystore -v*

Example:

  • Copy the SHA1 key and paste it in the certificate

  • Create the credentials

  • Copy your Client ID :[yourid].apps.googleusercontent.com or download the json

  • Once complete navigate back to the Google Play Console and refresh the credentials page and select your newly created OAuth credentials and save changes

  • Return to Play Games Services > Setup and management > Configuration

  • Create a Game Server Credential by clicking Add Credentials in the Configuration page under Setup and management

  • Select Type Game Server

  • Select Create OAuth client. Make sure to follow the link proposed

  • Select Application Type Web Application

  • Enter Project Name in the Name field

  • Select Create

  • Copy your Client ID and Client Secret or download json for future reference

  • Once complete Refresh OAuth clients in the Google Play Console and select your newly created OAuth credentials and save changes

  • Go to Play Games Services > Setup and management > Configuration> Credentials and click on Get Resources. Copy the resources

  • Continue to the next section

Unity Editor Setup Google Play Games

  • Download the version v11.01 play-games-plugin-for-unity

  • Open Unity Editor

  • Make sure your build settings are set to Android

  • Import the downloaded file by selecting Assets > Import Package >Custom Package

  • ***Enable the Auto Android Resolver if you do not have your own

  • Window > Google Play Games > Setup > Android Setup

  • Paste your copied xml Resources in the Resources Definition section

  • Copy the previously saved Web App Client ID and paste it in the field for the Optional Web App Client ID

  • Select Setup to save

Unity Authentication Editor Setup

  • Link your project to a corresponding dashboard project or create a new project id learn more

  • Select Edit > Project Settings > Services

  • Select Use an existing Unity project ID

  • Select corresponding Organization and dashboard project

  • To install the Authentication Package, Go to Window > Package Manager. Select Unity Registry from the packages drop down menu

  • Search for Authentication and install the package

  • To ensure the latest version of authentication click on + > Add package by name and enter com.unity.services.authentication into the field

  • In the Unity Editor menu, go to Edit > Project Settings > Services > Authentication

  • From the dropdown menu add Google Play games as an identity provider

  • Fill in Web App Client ID and Client Secret and save

Unity Script Setup

  • Create an empty game object

  • Create a script, call it GPManager and attach it to the newly created game object

  • Add the following code to load the authenticated user with google play games and Unity Authentication

using System;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System.Threading.Tasks;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;


public class GPManager : MonoBehaviour
{
    public string Token;
    public string Error;

    void Awake()
    {
        PlayGamesPlatform.Activate();
    }

    async void Start()
    {
        await UnityServices.InitializeAsync();
        await LoginGooglePlayGames();
        await SignInWithGooglePlayGamesAsync(Token);
    } 
    //Fetch the Token / Auth code
    public Task LoginGooglePlayGames()
    {
        var tcs = new TaskCompletionSource<object>();
        PlayGamesPlatform.Instance.Authenticate((success) =>
        {
            if (success == SignInStatus.Success)
            {
                Debug.Log("Login with Google Play games successful.");
                PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
                {
                    Debug.Log("Authorization code: " + code);
                    Token = code;
                    // This token serves as an example to be used for SignInWithGooglePlayGames
                    tcs.SetResult(null);
                });
            }
            else
            {
                Error = "Failed to retrieve Google play games authorization code";
                Debug.Log("Login Unsuccessful");
                tcs.SetException(new Exception("Failed"));
            }
        });
        return tcs.Task;
    }


    async Task SignInWithGooglePlayGamesAsync(string authCode)
    {
        try
        {
            await AuthenticationService.Instance.SignInWithGooglePlayGamesAsync(authCode);
            Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}"); //Display the Unity Authentication PlayerID
            Debug.Log("SignIn is successful.");
        }
        catch (AuthenticationException ex)
        {
            // Compare error code to AuthenticationErrorCodes
            // Notify the player with the proper error message
            Debug.LogException(ex);
        }
        catch (RequestFailedException ex)
        {
            // Compare error code to CommonErrorCodes
            // Notify the player with the proper error message
            Debug.LogException(ex);
        }
    }
}

Testing
Check if authentication is working by using Unity Logcat or Android studio Logcat.
You must connect your device to your workstation to view the Logcat.
A successful test will print out the following:

Unity Logcat (example):

Android Studio Logcat (example):

Additionally a visual queue will be displayed upon successful login.

Conclusion
This should get you started logging in to authentication and google play games generating and linking a user id between Google and Unity.

Links for further knowledge
Authentication documentation for Unity
https://docs.unity.com/authentication/en/manual/set-up-google-play-games-signin

Disable automatic sign in
https://www.hardreset.info/devices/apps/apps-google-play-games/disable-automatically-sign-in-to-supported-games/

22 Likes


This link is outdated, it gives error 404

2 Likes

The repo for the Google Play Games plugin for Unity:

https://github.com/playgameservices/play-games-plugin-for-unity

"NOTICE: This version of the plugin no longer supports iOS. Google Play games services for iOS is deprecated, and is not likely to function as expected. Do not use Google Play games services for iOS in new apps. See the deprecation announcement blog post for more details."

?

[quote=“GainfulSage”, post:3, topic: 911430]
The repo for the Google Play Games plugin for Unity:

https://github.com/playgameservices/play-games-plugin-for-unity

“NOTICE: This version of the plugin no longer supports iOS. Google Play games services for iOS is deprecated, and is not likely to function as expected. Do not use Google Play games services for iOS in new apps. See the deprecation announcement blog post for more details.”

?
[/quote]
Yes, Google Play Games hasn’t supported iOS since 2018. However, there are alternatives for sign in with Authentication on iOS devices such as:
Apple (unity.com)
and
Apple Game Center (unity.com)

Hi, thanks for the step by step guide. It is really helpful to clarify some ambiguities in the official documentation, such as not explicitly saying that you have to create a web credential.

I have a doubt. My project is open sourced. In the Unity Editor Setup Google Play Games section's steps my appId and client Id got saved in ../ProjectSettings/GooglePlayGameSettings.txt file (see attached image).

  1. What are the consequences of leaving these fields public?
  2. How can I avoid such consequences? if they exist

Thanks in advance and again for the guide.

8940927--1226466--ce-fizz-buzz – GooglePlayGameSettings.txt.jpg

I spent more than a week before I realized that the problem was in the proguard-user.txt file :eyes:

Unity version: 2019.4
Google Mobile Ads v7.1.0
Google Play Games v10.12
Target platform: Android

If you are using the "Custom Proguard File" option you must add the following lines to your proguard-user.txt file

-keep class com.google.android.gms.games.PlayGames { ; }
-keep class com.google.android.gms.games.leaderboard.
* { ; }
-keep class com.google.android.gms.games.snapshot.
* { ; }
-keep class com.google.android.gms.games.achievement.
* { ; }
-keep class com.google.android.gms.games.event.
* { ; }
-keep class com.google.android.gms.games.stats.
* { ; }
-keep class com.google.android.gms.games.video.
* { ; }
-keep class com.google.android.gms.games.
{ ; }
-keep class com.google.android.gms.common.api.ResultCallback { *; }
-keep class com.google.android.gms.signin.
* { ; }
-keep class com.google.android.gms.dynamic.
* { ; }
-keep class com.google.android.gms.dynamite.
* { ; }
-keep class com.google.android.gms.tasks.
* { ; }
-keep class com.google.android.gms.security.
* { ; }
-keep class com.google.android.gms.base.
* { ; }
-keep class com.google.android.gms.actions.
* { ; }
-keep class com.google.games.bridge.
* { ; }
-keep class com.google.android.gms.common.ConnectionResult { *; }
-keep class com.google.android.gms.common.GooglePlayServicesUtil { *; }
-keep class com.google.android.gms.common.api.
* { ; }
-keep class com.google.android.gms.common.data.DataBufferUtils { *; }
-keep class com.google.android.gms.games.quest.
* { ; }
-keep class com.google.android.gms.nearby.
* { *; }

Links
https://github.com/playgameservices/play-games-plugin-for-unity/blob/master/scripts/proguard.txt
https://stackoverflow.com/questions/61013678/google-play-games-service-in-unity-doesnt-authenticate

5 Likes


Before you make it open source you should remove your appID and ClientID and then instruct anyone wanting to use your open source project to use their own appID and ClientID.

1 Like


Hey thanks for the guide, I tried it but when I copy paste the SHA1 from my custom keystore that I use when building my game, I have an error on the SHA1
8955123--1229766--upload_2023-4-17_20-54-52.png
It's really odd because the SHA1 I get from my .keystore seems very long, if I chop it down the sha-1 gets approved but I'm 100% sure the authentication will fail.
Do you know what causes this and how to fix it ?
edit: otherwise my debug process is very very long I have to publish the app in an internal track in order to test it :/

Hi @rbitard ,
I had a similar error when I was redoing the steps. I tried to circumvent some steps by reusing a keystore.

Make sure your package name you have on the google dashboard matches the package name you registered when you create your keystore.

1 Like

Oh ! You are probably right since I created it a long time ago ! Thanks I'll try that


I retried and I have the same error.

I don't know what I'm missing
my game is com.unscripted.crapette so I put unscripted in my organization name.

What should I use to make it work ?

What is odd is that it's supposed to be the app upload key in google play store and when I go check it out
my sha1 in google play store is the MD5 when I type the command
and my sha256 is my sha1
8956320--1229958--upload_2023-4-18_10-13-53.png

I tried to use the MD5 when using keytool (that appears as the SHA1 in google APP-Integrity) and I have a sign in failed as I expected :(
(whereas when I upload using internal app sharing the sign in works because the sha1 is valid I guess)

it seems to work with the MD5 from keytool as the SHA1, which is odd, might be a fluke


Does it work with external testing rather than internal testing?

[quote=“Julian-Unity3D”, post:15, topic: 911430]
Does it work with external testing rather than internal testing?
[/quote]
it’s external testing by default I can’t select internal testing

1 Like


Well I'm glad you now have it working, I'm not too sure why it worked out that way for you, but at least its working

1 Like

Dunno if other have the same problem but it doesn't fully work with minify release ticked
https://github.com/playgameservices/play-games-plugin-for-unity/issues/3092
I had to untick it to solve the issue, is that ok to not use minify or is this a concern ?

2 Likes

Thanks for pointing that out rbitard and sharing that link. I will append it to the document as a requirement!
Minify helps decrease the size of your project. You should be fine without it unless you are really trying to minimize your application size by minimizing the code calls and classes. It detects any code or libraries that aren't being used and ignores them (in this case it seems those ignored libraries are causing problems)

2 Likes

I don't know if it's me but I can load the leaderboardUI but I can't post a score or load scores using Social.Active or PlaygamesPlatform.Instance

2023/04/22 13:39:38.412 32247 32291 Error Unity at _Scripts._4FrameworksAndDrivers.GameStateController+<>c.b__19_6 (GooglePlayGames.BasicApi.LeaderboardScoreData data) [0x00000] in <00000000000000000000000000000000>:0

I'm at the point of using the unity leaderboard beta and developing the UI myself :(
(which seems like a nice service too)