Skip to content

A detailed tutorial on how to implement Google Play Authentication in Unity with Firebase in 2023 using the new GooglePlayGamesPlugin-0.11.01

License

Notifications You must be signed in to change notification settings

Nichathan-Gaming/GooglePlayAuthenticationInUnityWithFirebase

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

Google Play Authentication In Unity With Firebase Android

A detailed tutorial on how to implement Google Play Authentication in Unity with Firebase in 2023 using the new GooglePlayGamesPlugin-0.11.01

Table of Contents

  1. Initial Setup and Details
    1. Disclaimer
    2. Details
    3. Before continuing you should have
  2. Instructions
    1. Firebase Setup
    2. Unity Setup 0
    3. Grabbing Unity's SHA1 key
    4. GitHub Privacy Policy
    5. Google Play Console Setup 0
    6. Google Cloud APIs & Services Setup
    7. Google Play Console Setup 1
    8. Unity Setup 1
    9. Unity Testing

Initial Setup and Details

Disclaimer

To the best of my knowledge, this walkthrough and all content inside of it has been typed with no errors or misinformation. That being said, neither I, nor Nichathan Gaming owns, has affiliation to, or any form of control over Unity, Google, the Google Console or Google Firebase. All information in this walkthrough is subject to become obsolete at any moment and there are no guarantees that anything inside of this walkthrough will work. By continuing to follow this walkthrough, you understand that neither Johnathan Nichols nor Nichathan Gaming are responsible for whatever may happen. That being said, I put a lot of time and effort into this walkthrough and I sincerely hope that it can help you.
Back To Top

Details

This walkthrough was typed by Johnathan Nichols of Nichathan Gaming on February 4th 2023. This guide was typed after months of casual intrigue and a week of serious contemplation over the authentication process. The walkthroughs purpose is to supplement the lack of documentation by Google Play Console, Unity and Firebase which all contain frustratingly outdated and useless documentation with nothing current or pointing to depreciated links.
Please note that this tutorial is only for Android Apps and does not cover Apple or IOS apps.
Back To Top

Before continuing you should have

  • A Google Play Account which costs around $25 (USD).
  • A Firebase account with the same Google Account as your Google Play account.
  • Download the current GooglePlayGamesPlugin which is 0.11.01 as of this posting.
  • The latest Unity LTS editor with Android modules installed.
  • A Console editor such as Command Prompt, Powershell, Hyper, etc...
  • An Android device to test/run your app on
    Back To Top

Instructions

Firebase Setup


1. From the Firebase Console click Add Project.
Firebase Console
2. Give the project any name, for the purpose of this tutorial, the project will be called GPGS. 1. For the purposes of this guide, you may enable or disable Google Analytics.
3. Click Create Project and wait for the project to be created.
4. In the project overview, under Get started by adding Firebase to your app, click the Unity icon.
Unity Icon
5. Under Register App, click the Register as Android app checkbox then: 1. Enter a package name for your project. This is com.CompanyName.AppName, if you do not have a company, any name works here. 2. Save the package name as we will use it in the Google Play Console and in the Unity Editor
6. Click Register app
Register App button
7. Download the google-services.json config file It will be added to our Unity project later
GSJSON Image
8. Download the Firebase Unity SDK (Zip) then: 1. Unzip the files anywhere. We will only use the Auth Unity Package but feel free to add others
Firebase SDK Image
Unzipped SDK
9. Click Continue to console
10. Navigate to Build/Authentication and click Get started
Get Started
11. Click the Google Sign-in method
Google Sign in method
12. Click Enable then add a public facing name and a support email. (The name is what is shown to users when Firebase sends them emails and the support email is where you receive emails from the user. This interaction is hands free and mediated through Firebase so no one knows the other's information.)
13. Click Save
Google Sign in method
14. Ignore the Download latest configuration file screen by clicking Done
pop up screen
15. Click the Google Sign-in method again and expand the Web SDK configuration drop-down, then: 1. Copy the Web client ID and Web client secret to your clipboard, notepad, word, etc... 2. Note: You can use the windows key and V to open your clipboard history win+V
WhatToCopy
16. Click Cancel
17. Click Add new provider then click Play Games
Add Play Games
18. Click Enable and paste your Client ID and Client Secret from step 15.1 into the fields.
19. Click Save
PG Add

Firebase Setup End


Back To Top

Unity Setup 0

Note: This walkthrough uses the Unity Editor 2021.3.16f1 which is the latest LTS version. If you encounter errors, first make sure that you are using the latest LTS version of Unity. You should also have the Android Build Support platform modules installed. I read that having iOS Build Support may clear some of the issues so I have it as well but I am unsure if it is useful or not.
Unity Setup
1. In the Unity Hub, click New Project
Note: This walkthrough should work in any existing projects but for the purposes of this walkthrough, we will create a vanilla project.
2. Select a project type and a project name, then click Create project.
Note: Your project can be any type but for the purposes of this walkthrough, we will use 2D Core with the name of GPGS
Create Project example
3. Once your Unity Editor finished building, navigate to and click File/Build Settings or press CTRL-SHIFT-B all at once.
Build Settings
4. If your project Platform is not already set to Android, click Android then click Switch Platform, otherwise, skip this step.
Switch Platform
5. Check Build App Bundle (Google Play) and set Create symbols.zip to public.
Settings
6. Click Player Settings and ensure that you are at Project Settings/Player once the new window opens.
Examples
7. Under Player set your Company Name and Product Name to fit the package name used in 5.1 of the Firebase Setup section.
Company/Product Name example
8. Navigate to Other Settings to Identification and either unselect Override Default Package Name or type it manually into the Package Name input field.
Package Name IF
9. Set the Target API Level to the highest available unless you are certain that you have the highest installed already. Note: This will install the highest Android API level when you build your app and you can use Automatic(highest installed) from here on out.
image
10. Under Player/OtherSettings/Configuration set Scripting Backend to IL2CPP and select ARM64.
Config
11. Now, move from Player/Other Settings to Player/Publishing Settings and click Keystore Manager...
keystore manager button
12. In the pop-up window, click Keystore.../Create New/Anywhere... then save the keystore under any filename, as long as the file extension is .keystore and click Save.
Create new keystore
13. Enter any password, then under New Key Values fill out the required fields to click Add Key
Key manager
14. At the new pop-up screen Keystore and Key created click Yes
pop up keystore

Unity Setup 0 End


Back To Top

Grabbing Unitys SHA1 key

Note: Now, we will grab the SHA1 key which we just created in step 13 of Unity Setup 0. To do this, we must work in a console. This may be Command Prompt, PowerShell, Hyper, or any other console. Please, be careful with the commands that you type into your console, especially if you are untrained. While you shouldn't be able to seriously damage anything since you have few permissions until you know how to get them, there is still a chance that you can do damage if you deviate from the commands shown in this walkthrough. For the purposes of this walkthrough, we will use Hyper but the commands should still work in any other console. Please note as well that in console commands, they use the word directory instead of folder. Some useful console commands are ls (lists all files and directories in the current directory), cd .. (navigates to the directory that holds this directory), cd /path/ (navigates to the directory at the given path). Also, you should not be able to use CTRL+C or CTRL+X to copy or cut text. Instead, you may need to use the right mouse button to copy in consoles.
1. First, we must identify the directory where we saved our keystore. If you followed along, this should be in our project folder. Although, your Keystore Manager should show you the path. From the image below, you can see that my keystore is in my project folder under the file name user.keystore.
path loc
2. Now open your console or terminal and navigate to the path of your keystore. To see where you are, use 'ls', to move back use 'cd ..', to move forward use 'cd PATHNAMEHERE'.
Hyper
3. Once you are at your user.keystore location (or whatever you named your .keystore file as), type 'keytool -keystore KEYSTORE FILE NAME -list -v' replacing 'KEYSTORE FILE NAME' with the name of your .keystore file. Then, enter your password that you used to create your .keystore file in step 13 of Unity Setup 0.
GetSHA1
4. Finally, highlight and copy your SHA1 certificate fingerprint. Remember, you may need to use the right mouse button to copy in your console.
CopySHA1

Grabbing Unitys SHA1 key End


Back To Top

GitHub Privacy Policy

Note: The Google Play Console requires all apps to have a privacy policy. That being said, all a privacy policy is, is pretty much a notice of intent. You can host your privacy policy on GitHub or on your personal website. However, GitHub is free and easy to use. However, if GitHub or your GitHub account are taken offline or deleted, your app may be forcefully unpublished until a new privacy policy is provided.
1. Navigate to the new repository section of GitHub
2. Enter a repository name such as GPGSPrivacyPolicy, check Add a README file and click Create repository
image
3. Inside your new repository, click the pencil next to your README.md file to edit it.
Repo Edit
4. Add content similar to that shown below and click Commit changes

I hereby state, to the best of my knowledge and belief, that I have not programmed this app to collect any personally identifiable information. All data created by you (the user) is stored on your device only, and can be erased by clearing the application's data or by uninstalling the application.


5. Copy and save the link to your GitHub Repository. For example, mine is https://github.com/Nichathan-Gaming/GPGSPrivacyPolicy.

GitHub Privacy Policy End


Back To Top

Google Play Console Setup 0

Note: Remember, you must purchase a Google Play Console account first which costs around $25 (USD) at the time that this walkthrough was published. Costs are subject to increase or decrease at any time.
1. In the Google Play Console, while logged in, click Create app
GPC
2. Fill out the App details. I do not believe that App name, Default Language nor Free or Paid matters but to use the Google Play Games Console you must select Game under App or game
app details
3. Then click, Create app in the bottom right of the screen.
4. Navigate to Grow/Store presence/Main store listing and fill out the app details to the best of your abilities. Then click Save Note: You must provide descriptions of at least 1 character, a 512x512 image, a 1024x500 image and at least 2 9x16 images in the Phone and Tablet sections.
MSL
5. Navigate down to Store settings in the same area and fill out the settings to the best of your abilities. Then click Save.
SS
6. Scroll to the very bottom to App Content and fill out all parts of the To do to the best of your abilities. Do this one at a time by clicking Start. Ensure that you always save when are done with a field.
TODO
completed
7. After, you're all done with part 6, scroll up to Grow/Play Games Services/Setup and management/Configuration, select *Yes, my game already uses Google APIs, select your Firebase project from the Cloud project drop-down and click Use in the bottom right.
Config Setup
8. In the same area, to the right of Credentials, click Add credentials
AddCred
9. Click Create OAuth client then follow the link to Create OAuth Client ID.
follow link

Google Play Console Setup 0 End


Back To Top

Google Cloud APIs & Services Setup

Note: Ensure that you are always in the current project. If you ever leave the web page and return, you may need to re-select your project.
GCAPI
1. Click + CREATE CREDENTIALS then OAuth client ID
OAuth
2. Select Android for your Application type, use the Package Name used in Firebase and in your Unity project and add the SHA-1 certificate fingerprint from step 4 Grabbing Unitys SHA1 key then click CREATE.
OAUTH ex
3. In the popup, download the JSON file and click OK
popup

Google Cloud APIs & Services Setup End


Back To Top

Google Play Console Setup 1

Note: Make sure that you have done all of the previous steps before reaching this part. We will continue from the last step of Google Play Console Setup 0.
1. Back in the Google Play Console/Grow/Play Games Services/Setup and management/Configuration/Add credential screen, go down to Authorization, click Refresh OAuth clients and select the newly created client in the drop down. Click Save changes and go back to Configuration Note: There should only be 1 option. If not, ensure that Type is still Android.
Android Cred
2. Click Add Credential again, select Type as Game server, click Refresh OAuth clients and in the drop down, select the option that has the same Client ID as your Firebase Google Sign-in method. Then click Save changes and go back to Configuration.
FBCID
CredOption
3. Click Get Resources and copy the Android(XML). Note: This will not be used until Unity Setup 1 so save it in a safe space.
button
XML
4. Click Review and publish.
RAP
5. If you have actions required in your properties, click the arrow and fill out all of the information in the new area. Note: Wait for the images to finish uploading before clicking the Save changes button.
Update
Filled out
6. Return to Configuration then click Review and Publish. You should now be able to click the Publish button. If not then you should see required fields that you neglected to fill out. At the pop-up, confirm the publish.
publish btn

Google Play Console Setup 1 End


Back To Top

Unity Setup 1

Note: If you closed Unity at any time since Unity Setup 0, you will need to reenter your keystore password in Project Settings/Player/Publishing Settings.
1. Go to Assets/Import package/Custom package then import the Firebase Auth unity package and the GooglePlayGamesPlugin-0.11.01.unitypackage. Note: It should be fine if there is a newer version of the Google Play Games Plugin package. You should always use the newest stable version. Also, ensure that you import all files when prompted.
Menu
GPGP
FBAUTH
2. While importing the Google Play Games Plugin you may see a screen similar to the picture below. Enable Anroid Auto Resolution and Delete old files.
Pop Up GPGP
3. Navigate to Window/Google Play Games/Setup/Android Setup... and click on it.
button
4. In the Google Play Games - Android Configuration pop-up screen, paste your XML from step 3 of Google Play Console Setup 1 in the big box, paste your Firebase Google Client ID where it says Client ID then click Setup.
setup
success
5. Now, you need to import the JSON files from step 7 of Firebase Setup and step 3 of Google Cloud APIs & Services Setup.
6. Go to Assets/External Dependency Manager/Android Resolver/Force Resolve and click to force resolve.
force resolve
Note: We will now setup scripts to test the authentication. You are already setup to use the authentication and no longer have to follow this guide religiously. You can skip to step 12 Foundation Code for the code, or follow along to log results to your device screen. Also, remember that this will not work on your computer. You can only test or run Google Play authentication in Unity with Firebase on your mobile Android device. Because of this, I will add a TMP_Text object to my screen to see results.
7. Right click in the Hierarchy and create a UI/Scroll View. Then delete the Content and both Scrollbars.
delete
8. Right click on Viewport and add a UI/Text(TMP) then import TMP essentials.
TMPPRO
9. Select the Canvas in the Hierarchy and set the Canvas Scalar values to those shown below.
CanvasScalar
10. On the Text (TMP) object, add a Content Size Fitter with a vertical fit to Preferred Size and set the Anchors and Pivots to those shown below. Also, set the Font Size very high, we will use 100 to make it more visible.
TEXTTMP
11. Select the Scroll View in the Hierarchy and delete the Image and Canvas Renderer components. Drag Text (TMP) to the Scroll Rect Content area and set the Anchors and Pivots to those shown below.
ScrollView
12. In Project/Assets right click and create a new C# script. Name it whatever you wish but for the purposes of this walkthrough, we will name it 'Auth'.
Create
13. Open the script in your favorite script editor. For the purposes of this walkthrough, we will use the Unity default Visual Studio. Then copy either the Foundation Code or the Debugging Code below.
Back To Top

Foundation Code

using Firebase.Auth;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine;

public class Auth : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        PlayGamesPlatform.Instance.Authenticate(status =>
        {
            if (status == SignInStatus.Success)
            {
                PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
                {
                    FirebaseAuth auth = FirebaseAuth.DefaultInstance;
                    Credential credential = PlayGamesAuthProvider.GetCredential(code);
                    auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
                    {
                        if (task.IsCanceled)
                        {
                            // canceled
                        }
                        else if (task.IsFaulted)
                        {
                            // error  task.Exception
                        }
                        else
                        {
                            FirebaseUser newUser = task.Result;
                        }
                    });
                });
            }
        });
    }
}


Back To Top

Debugging Code

using Firebase.Auth;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
using System.Collections;
using TMPro;
using UnityEngine;

public class Auth : MonoBehaviour
{
    [SerializeField] TMP_Text textBox;

    // Start is called before the first frame update
    void Start()
    {
        try
        {
            textBox.text += "Authenticate";
            //Auth with Google Play
            PlayGamesPlatform.Instance.Authenticate(status =>
            {
                if (status == SignInStatus.Success)
                {
                    textBox.text += "\nSuccess\nRequestServerSideAccess";

                    try
                    {
                        //Ask for Auth code - This is why we need the Web Server Client ID's and secrets from Firebase
                        PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
                        {
                            FirebaseAuth auth = FirebaseAuth.DefaultInstance;
                            Credential credential = PlayGamesAuthProvider.GetCredential(code);

                            //move Firebase get to Coroutine so we can log to our textbox
                            StartCoroutine(AuthGet());

                            IEnumerator AuthGet()
                            {
                                System.Threading.Tasks.Task<FirebaseUser> task = auth.SignInWithCredentialAsync(credential);

                                while (!task.IsCompleted) yield return null;

                                if (task.IsCanceled)
                                {
                                    textBox.text += "\ncanceled";
                                }
                                else if (task.IsFaulted)
                                {
                                    textBox.text += "\nerror " + task.Exception;
                                }
                                else
                                {
                                    FirebaseUser newUser = task.Result;
                                    textBox.text += "\n\nFULLY AUTHENTICATED\n\n";
                                    textBox.text += newUser.ToString();
                                }
                            }
                        });
                    }
                    catch (Exception e)
                    {
                        textBox.text += "RequestServerSideAccess error\n" + e.ToString();
                    }
                }
                else textBox.text += "Failure";
            });
        }
        catch (Exception e)
        {
            textBox.text += "Authenticate error\n" + e.ToString();
        }
    }
}

Unity Setup 1 End


Back To Top

Unity Testing

Note: For the purposes of this walkthrough, we will use the Debugging Code. If you are just here for the code then this tutorial is finished.
1. Back in the Unity Editor, right click on the Hierarchy and click Create Empty which creates an empty game object. We will name it Auth and drag our new Auth script onto it.
emptyAuth
2. Drag the Text (TMP) to Auth where it says Text Box.
AuthFinal
3. Click File/Build and Run or press CTRL+B at the same time and save the aab file under any name and in any folder. For the purposes of this walkthrough, we will create a new Builds folder and save the file as GPGS.aab there.
build&run
SAve
Note: Ensure that you have a mobile Android device with MIDI connection and Unity Remote 5 connected to your computer. You may even need to set the device in your project settings. An alternative is to build the .aab file and then transfer onto your mobile device then install it there.

Run Results

RR

Run Results End

Unity Testing End

About

A detailed tutorial on how to implement Google Play Authentication in Unity with Firebase in 2023 using the new GooglePlayGamesPlugin-0.11.01

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published