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

Domenico Rotolo
Nov 26, 2019 · 7 min read

Before we begin…

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:

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:

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:

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!

The Startup

Get smarter at building your thing. Join The Startup’s +724K followers.

Domenico Rotolo

Written by

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

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Domenico Rotolo

Written by

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

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store