You can let your users authenticate with Firebase using their Google Accounts by
integrating Google Sign-In into your app.

## Before you begin

### Set up your Unity project

Before you can use
[Firebase Authentication](https://firebase.google.com/docs/reference/unity/namespace/firebase/auth.md.txt),
you need to:

- Register your Unity project and configure it to use Firebase.

  - If your Unity project already uses Firebase, then it's already
    registered and configured for Firebase.

  - If you don't have a Unity project, you can download a
    [sample app](https://github.com/google/mechahamster).

- Add the [Firebase Unity SDK](https://firebase.google.com/download/unity) (specifically, `FirebaseAuth.unitypackage`) to
  your Unity project.

> [!NOTE]
> **Find detailed instructions for these initial
> setup tasks in
> [Add Firebase to your Unity project](https://firebase.google.com/docs/unity/setup.md.txt#prerequisites).**

Note that adding Firebase to your Unity project involves tasks both in the
[Firebase console](https://console.firebase.google.com/) and in your open Unity project
(for example, you download Firebase config files from the console, then move
them into your Unity project).

### Set up your Firebase project and credentials

1. **Android:** Specify your app's SHA-1 fingerprint in the
   Firebase console:

   1. In the Firebase console, go to **Settings** \> [**General** tab](https://console.firebase.google.com/project/_/settings/general/).
   2. Go to the **Your apps** card, select your Android app, and add
      your SHA-1 fingerprint in the **SHA certificate fingerprints** field.

      You can retrieve your keystore's SHA-1 fingerprint using `keytool`:

      ```bash
      keytool -keystore path-to-keystore.keystore -list -v
      ```

      See [Authenticating Your Client](https://developers.google.com/android/guides/client-auth)
      for more details on getting your app's SHA fingerprint.
2. **Enable Google Sign-In and copy your Web client ID:**

   1. In the Firebase console, go to **Security** \> [**Authentication**](https://console.firebase.google.com/project/_/authentication/).
   2. In the **Sign-in method** tab, enable the **Google** sign-in provider.
   3. Expand the **Web SDK configuration** section and copy your **Web client
      ID** (for example, `123456-abc.apps.googleusercontent.com`). This represents the audience (`aud`) claim of your ID tokens and is required for both Android and iOS.
   4. Click **Save**.

   > [!NOTE]
   > **Tip:** If you prefer to use the [Firebase CLI](https://firebase.google.com/docs/cli.md.txt), run `firebase init auth` to configure authentication providers, and then run `firebase deploy --only auth` to deploy the changes to your project.

   > [!NOTE]
   > **Note:** Enabling Google Sign-In in the Firebase console automatically provisions OAuth 2.0 client IDs for your registered apps. You can also view and manage your OAuth consent screen and client IDs on the [**Credentials** page](https://console.cloud.google.com/apis/credentials) in the Google Cloud console.

3. **Update your Firebase config files and copy your iOS reversed client ID:**

   1. Download the latest Firebase configuration files from the Firebase console (`google-services.json` for Android and `GoogleService-Info.plist` for iOS) and replace any older copies in your Unity project. (See [Add Firebase to your Unity project](https://firebase.google.com/docs/unity/setup.md.txt#add-config-file).)
   2. **iOS:** Open your `GoogleService-Info.plist` file and copy the value of the `REVERSED_CLIENT_ID` key (for example, `com.googleusercontent.apps.12345-abc`). This value is required to configure the iOS redirect URL scheme.

## Integrate the Google Sign-In plugin into your Unity project

1. **Import the plugin:**

   1. If you are integrating into an existing project, back up your project and remove any older Google Sign-In plugins before proceeding.
   2. Download `GoogleSignInNative.unitypackage` [from GitHub](https://github.com/googlesamples/siwg-mobile-unity-plugin) and import it into your Unity project (**Assets \> Import Package \> Custom Package** ). Ensure all files are selected and click **Import**.

   > [!CAUTION]
   > **Caution:** This plugin includes `baseProjectTemplate.gradle` and `settingsTemplate.gradle`. If your project does not already have custom Gradle templates, they are added automatically. If your project already uses custom Gradle templates, Unity won't overwrite them; you must manually merge the Kotlin `1.9.24` definitions from the plugin into your existing templates.

2. **Configure plugin settings:**

   1. In the Unity Editor, go to **Window \> Google Sign-In Native \>
      Settings**.
   2. Paste your **Web Client ID** into the first field.
   3. Paste your **iOS Reversed Client ID** into the second field.
   4. Click **Save Settings**.
3. **Resolve native dependencies:**

   1. Go to **Assets \> External Dependency Manager \> Android Resolver \> Force
      Resolve**.
   2. Wait for the success message. This downloads the native `googleid` and `androidx` Credential Manager libraries.

## Access the `Firebase.Auth.FirebaseAuth` class

The `FirebaseAuth` class is the gateway for all API calls. It is accessible through [FirebaseAuth.DefaultInstance](https://firebase.google.com/docs/reference/unity/class/firebase/auth/firebase-auth.md.txt#defaultinstance).

```c#
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
```

## Authenticate with Firebase

1. **Set up `GoogleSignInManager` in your scene:**

   1. Create an empty `GameObject` in your initial scene named `GoogleSignInManager`.
   2. Attach the `GoogleSignInManager.cs` script to it.
   3. Drag the `GoogleSignInNativeSettings` asset (located in `Assets/GoogleSignInNative/Resources`) into the **Sign In Settings** slot on the script.
2. **Trigger Google Sign-In and exchange the ID token for a Firebase
   credential:**

   Create a controller script that subscribes to
   `GoogleSignInManager.OnSignInCompleted` and
   `GoogleSignInManager.OnSignInFailed`, triggers sign-in with
   `GoogleSignInManager.Instance.StartSignIn()`, and exchanges the resulting
   Google ID token for a Firebase credential using
   `GoogleAuthProvider.GetCredential`:

   ```c#
   using Firebase.Auth;
   using Firebase.Extensions;
   using UnityEngine;

   public class MyAuthController : MonoBehaviour
   {
       private FirebaseAuth auth;

       private void Awake()
       {
           auth = FirebaseAuth.DefaultInstance;
       }

       private void OnEnable()
       {
           GoogleSignInManager.OnSignInCompleted += HandleSignInSuccess;
           GoogleSignInManager.OnSignInFailed += HandleSignInFailure;
       }

       private void OnDisable()
       {
           GoogleSignInManager.OnSignInCompleted -= HandleSignInSuccess;
           GoogleSignInManager.OnSignInFailed -= HandleSignInFailure;
       }

       public void OnSignInButtonClick()
       {
           GoogleSignInManager.Instance.StartSignIn();
       }

       private void HandleSignInSuccess(string idToken)
       {
           Debug.Log("[Auth] Google Sign-In succeeded. Authenticating with Firebase...");

           Credential credential = GoogleAuthProvider.GetCredential(idToken, null);
           auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWithOnMainThread(task => {
               if (task.IsCanceled)
               {
                   Debug.LogError("SignInAndRetrieveDataWithCredentialAsync was canceled.");
                   return;
               }
               if (task.IsFaulted)
               {
                   Debug.LogError("SignInAndRetrieveDataWithCredentialAsync encountered an error: " + task.Exception);
                   return;
               }

               AuthResult result = task.Result;
               Debug.LogFormat("User signed in successfully: {0} ({1})",
                   result.User.DisplayName, result.User.UserId);
           });
       }

       private void HandleSignInFailure(string error)
       {
           Debug.LogError($"[Auth] Google Sign-In failed: {error}");
       }
   }
   ```

## Build your app

### Android

- Ensure your **Package Name** in **Player Settings** matches your Firebase and Google Cloud OAuth credentials exactly.
- Ensure your **Minimum API Level** is set to **34** or higher.
- Click **Build and Run**.

### iOS

- Build your project in Unity to generate an Xcode project, then open the generated `.xcworkspace` file.
- In Xcode, go to the **Signing \& Capabilities** tab and select your **Development Team**.
- The plugin automatically adds the custom URL scheme (`REVERSED_CLIENT_ID`) to your Xcode project. Build and run on a physical device.

## Next steps

After a user signs in for the first time, a new user account is created and
linked to the credentials---that is, the user name and password, phone
number, or auth provider information---the user signed in with. This new
account is stored as part of your Firebase project, and can be used to identify
a user across every app in your project, regardless of how the user signs in.

- In your apps, you can get the user's basic profile information from the
  [`Firebase.Auth.FirebaseUser`](https://firebase.google.com/docs/reference/unity/class/firebase/auth/firebase-user.md.txt) object:

  ```c#
  Firebase.Auth.FirebaseUser user = auth.CurrentUser;
  if (user != null) {
    string name = user.DisplayName;
    string email = user.Email;
    System.Uri photo_url = user.PhotoUrl;
    // The user's Id, unique to the Firebase project.
    // Do NOT use this value to authenticate with your backend server, if you
    // have one; use User.TokenAsync() instead.
    string uid = user.UserId;
  }
  ```
- In your Firebase Realtime Database and Cloud Storage
  [Security Rules](https://firebase.google.com/docs/database/security/user-security), you can
  get the signed-in user's unique user ID from the `auth` variable,
  and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authentication
providers by [linking auth provider credentials to an
existing user account.](https://firebase.google.com/docs/auth/unity/account-linking)

To sign out a user, call [`SignOut()`](https://firebase.google.com/docs/reference/unity/class/firebase/auth/firebase-auth.md.txt#signout):

```c#
auth.SignOut();
```