Firebase Authentication in Unity with Google & other providers using REST APIs

Domenico Rotolo
The Startup
Published in
7 min readNov 26, 2019

--

Before we begin…

  • Do you find learning easier if it comes from a video? If so, you can find the video lesson of this article right here! Sit back, grab your popcorns and start watching!
  • Alternatively, if you have just clicked on this article for the code, here it is! Go ham!

What we’ll be using

Here’s a recap of the external libraries we will use, in case you haven’t had the chance to read the previous article yet:

Okay, let’s do this!

To successfully sign in using an external provider, we’ll need to complete these 3 simple steps:

Step 0 (because any respectable list should start from zero): Some UI
Just some basic UI
to make our Application work, nothing too fancy!

Step 1: Ask permission to the user
The user will be redirected to a page where they can sign in using their providers and can grant any required permissions! In exchange, the application will get a code!

Step 2: Exchange the code for an access token
The code
we’ve received from Step 1 can now be converted into an access token that we can later plug into Firebase!

Step 3: Plug the access token into Firebase
This will create a new user on Firebase (if there isn’t one already) and will return us a bunch of useful info about our user as well as an idToken, that can be used to authenticate any requests (Yay we did it!).

Note: Step 1 and Step 2 will depend on the type of provider you use (Google, Facebook, Twitter…) while Step 3 will always be consistent! For this article, we are going to use Google as a provider!

Step 0: Some UI

So let’s create a scene with some basic UI elements:

Some scene with two buttons and one input field

Next up let’s create a UIHandler.cs class, that will take care of all our UI needs, just so that’s out of the way and we can focus on the rest!

Finally, let’s attach this script to the Camera and let’s link the two functions to the two buttons; we should also set the reference to the input field gameobject. We can do this all from the inspector:

Step 1: Ask permission to the user

Now that we are done with the UI, we can finally get into the swing of things!
Let’s make a new class (GoogleAuthenticator.cs) that will handle everything that we need from our provider (as I said above, we’ll use Google for this example).

To make the user authenticate, we simply have to open a webpage to this endpoint:

https://accounts.google.com/o/oauth2/v2/auth

Luckily, Unity has an easy method to accomplish just that:

The endpoint requires some parameters! Let’s quickly review the mandatory ones:

  • client_id: The client ID for our application! We’ll generate this later…
  • redirect_uri: The page the user gets redirected to after they’ve granted their permissions. Keep this in mind, we’ll talk more about it in a minute!
  • response_type: For our purposes, it should be “code”.
  • scope: The actual permissions we need from our user… we are simply going to set this to “email” for this tutorial, but you can find more here!

There are more parameters but they are not required! You can find them here!

Let’s get the parameters!

Go to your Firebase Project or create a new one!
Navigate to Authentication -> Sign-in method -> Enable the Google sign-in provider.

Such a pleasure to meet you, project. How are you?

Do you see those credentials under “Web SDK configuration”? Good, forget about those, because we are going to be creating our own from the Google Cloud Platform!

Make sure to select the “OAuth client ID” one

Let’s copy the client_id and client_secret and store them in our class!

So now let’s talk about how are we going to communicate the access code to our application. This is where the redirect_uri comes in…

For the sake of simplicity, we’ll be using a basic manual copy/paste method which means that the user will receive the code directly and they will then copy it and paste it into our App (in the input field).

Keep in mind though that, although this is the simplest method to implement, it isn’t the best one. The loopback IP address option provides a more reliable, secure, and user-friendly way to obtain user authorization.

Depending on the method you end up using, the redirect_uri will have to be different. Here’s the one for the manual copy/paste method:

urn:ietf:wg:oauth:2.0:oob

Let’s add the parameters!

Finally, let’s add all the parameters we found into the endpoint URL:

Step 2: Exchange the code for an access token

At the moment, when the GetAuthCode() function is called, the user will be able to sign in, grant permission, and copy/paste the code onto our input field! Let’s now convert this code into something we can plug into Firebase!

Let’s do the request!

We’ll need to do an empty POST request to this endpoint:

https://oauth2.googleapis.com/token

Here are the parameters we need for the request:

  • code: The code we got from Step 1.
  • client_id
  • client_secret
  • redirect_uri: It can be the same one we used for Step 1.
  • grant_type: For our purposes, it should be “authorization_code”.

There are more parameters but they are not mandatory! You can find them here!

It will return us this JSON object:

Note that all we need is either the access_token or the id_token.
We’ll snatch the id_token!

To make the actual request, we’ll be using the RestClient Library, which you can find here, or that you can download from the Unity Asset Store here!

Let’s make the ExchangeAuthCodeWithIdToken() method:

Let’s fetch that response!

Let’s transform that JSON string into an object which will have our id_token!

We can do this simply by using the FullSerializer Library, which you can find here! The developers were kind enough to include an API class which can make us Serialize/Deserialize JSON easily:

Let’s create the object the JSON will be deserialized into:

Note: make sure not to change the name of the id_token variable or the deserialization won’t work properly.

And finally… let’s get back on our ExchangeAuthCodeWithIdToken() method and write the code. Let’s also create an Action<string> parameter so that we can pass the id_token in a callback like this:

And just like that, Step 2 is complete!

Step 3: Plug the access token into Firebase

This will return us info about our Firebase user and, if it’s the first time they are logging in, it will create a new one!

All of this gets handled automagically by sending a POST request with a payload to this endpoint:

https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=[API_KEY]

You can find the API_KEY in your Firebase Project’s settings:

This is the JSON payload the request needs:

{“postBody”:”id_token=[idToken]&providerId=[providerId]”,”requestUri”:”http://localhost","returnIdpCredential":true,"returnSecureToken":true}

The only fields we need to change are the id_token and the providerId:

  • id_token: The one we got from Step 2.
  • providerId: It’s google.com if you are using Google as a provider.

If you are curious, you can learn more about the other fields here!

Note: If in Step 2 you fetched the access_token instead of the id_token, be sure to change the “id_token=[idToken]” part of the payload to “access_token=[accessToken]”.

Since, as we said at the beginning of the article, Step 3 is constant no matter what provider you are using, let’s write the code for it in a new class, FirebaseAuthHandler.cs!

Let’s call these functions!

Hurray, all 3 steps are completed! Let’s now call these functions in our UIHandler.cs class, like this:

The moment of truth…

Let’s see if what we created works:

What’s Next?

Now that you’ve got all the info about the user from Step 3, you are ready to authenticate your requests! Luckily for you, I have made an article about this a while back… you can read it here!

Finally, remember you can check out all the code shown in this article on Github!

--

--

Domenico Rotolo
The Startup

I am Unity game-maker! Big fan of open source and games!