> ## Documentation Index
> Fetch the complete documentation index at: https://archie.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Firebase

> Accept Firebase Authentication and Google Cloud Identity Platform ID tokens in your Archie backend. Set up the provider, restrict who can sign in, turn on revocation checks, and troubleshoot rejected tokens.

The Firebase provider lets your Archie backend accept the ID tokens that Firebase Authentication or Google Cloud Identity Platform issue to your users. Your app keeps signing users in with Firebase. Archie only checks the token.

Archie validates every ID token locally. It checks the RS256 signature against Google's public `securetoken` keys, then checks the project, issuer, expiry, and your restrictions. It's the same ID token your app already sends to Google Cloud services, so you don't need a second sign-in.

To open it, navigate to **App Services → Authentication Providers** in the Backend Console and add a **Firebase** provider.

## How requests work

Your app gets the ID token from the Firebase SDK and sends it on every request to your Archie backend.

| Header | Value |
| - | - |
| `Authorization` | `Bearer <idToken>` |
| `x-project-id` | Your Archie project ID. |
| `environment` | Optional. Your environment name. Defaults to `master` when omitted. |

Archie reads the ID token only from the `Authorization` header, with the `Bearer` scheme.

If the request has no `Authorization` header at all, Archie answers `401` with the message `Missing required headers: x-project-id and/or authorization`. That response has no `extensions.code`, because no token reached the provider.

```ts theme={null}
import { getAuth } from 'firebase/auth';

const user = getAuth().currentUser;
const idToken = await user.getIdToken(); // the Firebase SDK refreshes it when needed

const response = await fetch('https://your-gateway.example.com/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${idToken}`,
    'x-project-id': 'your-project-id',
    'environment': 'master',
  },
  body: JSON.stringify({ query: '{ __typename }' }),
});
```

> [!NOTE]
>
> Always ask the Firebase SDK for the token right before the request. ID tokens expire after one hour, and `getIdToken()` returns a fresh one when the current token is about to expire.

## Before you start

Collect these values from Google.

### Firebase Project ID

1. Open the [Firebase console](https://console.firebase.google.com/) and select your project.
2. Click the gear icon, then **Project settings**.
3. Copy the **Project ID** from the **General** tab.

The Project ID is not the project name and not the project number. It looks like `my-app-1a2b3`.

### Identity Platform Tenant ID (only for multi-tenancy)

Skip this if you don't use Identity Platform tenants.

1. Open the [Google Cloud console](https://console.cloud.google.com/) and select the same project.
2. Navigate to **Identity Platform → Tenants**.
3. Copy the **Tenant ID** of the tenant your users sign in to.

### Issuer

You don't enter the issuer. Archie derives it from the Project ID and shows it read-only:

```
https://securetoken.google.com/<projectId>
```

## Configure the provider

The form has four sections. Click **Save** when you're done.

### General

| Field | Default | What it does |
| - | - | - |
| **Provider Name** | — | Required. A name that identifies this provider in the console. 3–64 characters, and unique among the providers of the environment. |
| **Description** | Empty | Optional notes for your team. Up to 255 characters. |
| **Firebase Project ID** | — | Required. Tokens must be issued for this project. 6–30 characters: lowercase letters, digits, and hyphens, starting with a letter. |
| **Tenant ID** | Empty | Optional. When set, only tokens from this Identity Platform tenant are accepted. When empty, tokens that carry a tenant are rejected with `token_invalid_tenant`, so set it if your users sign in to an Identity Platform tenant. The format is checked when you save: 4–64 letters, digits, and hyphens, starting with a letter and not ending with a hyphen. |

### Restrictions

| Field | Default | What it does |
| - | - | - |
| **Allowed Sign-in Providers** | Empty | Limits the Firebase sign-in methods whose tokens are accepted, for example `password`, `google.com`, or `apple.com`. Archie reads them from the token's `firebase.sign_in_provider` claim. Up to 50 entries. |
| **Allow Anonymous Users** | Off | Accepts tokens from Firebase anonymous sign-in. It has no effect in this version: anonymous users have no email, so their tokens are rejected even with this option on. See the note below. |
| **Require Verified Email** | On | Rejects tokens whose `email_verified` claim is not `true`. |
| **Allowed Email Domains** | Empty | Accepts only users whose email domain is an exact match for one of the listed domains. `example.com` doesn't match `sub.example.com`. This check uses the email address in the token. It is not the same as Google's Hosted Domain (`hd`) setting. Up to 50 entries. |
| **Max Auth Age** | — | In minutes. Rejects tokens when the user's last sign-in (the `auth_time` claim) is older than this. Use it to force users to sign in again periodically. |

> [!WARNING]
>
> In this version, every token must carry an email address. Tokens without an email, such as phone sign-in and anonymous sign-in tokens, are rejected with `token_policy_rejected`, even when **Allow Anonymous Users** is on and **Require Verified Email** is off.

### Revocation

By default, Archie accepts a valid token until it expires, even if you revoke the user's sessions or disable the account in Firebase. Turn on revocation checks to close that gap.

| Field | Default | What it does |
| - | - | - |
| **Check Revoked Tokens** | Off | Asks Google whether the user's tokens were revoked or the account was disabled. |
| **Service Account Key** | Empty | Required when **Check Revoked Tokens** is on. Paste the JSON key of a service account from the same Firebase project. |

The key must be a JSON key of type `service_account` that belongs to the same project as the **Firebase Project ID**. After you save, the console shows the key masked. To keep the stored key when you edit the provider, leave the field empty.

**Check Revoked Tokens** can't be combined with **Additional Project IDs**. The service account can only check revocation in the main project, so a configuration with both is rejected when you save. If you need revocation checks, accept tokens from a single Firebase project.

See [Set up the service account for revocation](#set-up-the-service-account-for-revocation).

### Advanced

| Field | Default | What it does |
| - | - | - |
| **Additional Project IDs** | Empty | Other Firebase projects whose tokens are also accepted. Each one uses its own issuer, `https://securetoken.google.com/<projectId>`. Up to 10 projects. Can't be combined with **Check Revoked Tokens**. |
| **Clock Skew** | 60 seconds | Tolerance for clock differences when checking token times. From 0 to 300 seconds. |
| **Token Location** | — | Reserved. The value is validated and stored, but it isn't applied yet: Archie only reads the token from the `Authorization: Bearer` header (see [How requests work](#how-requests-work)). Leave it empty. |
| **User ID Claim** | — | The claim that identifies the user. Firebase puts the user's UID in `sub`. |
| **Email Claim** | — | The claim that holds the user's email. Firebase uses `email`. |
| **Display Name Claim** | — | The claim that holds the user's name. Firebase uses `name`. |
| **Roles Claim** | Off | Reads role names from a custom claim that you set with the Firebase Admin SDK. Administrative role names in the claim are ignored. |
| **Allowed Roles** | Empty | Required for the claim to grant any role. The roles from the claim that Archie may grant, matched exactly. Each one must be an existing role of the project environment, and it can't be administrative or privileged. Up to 20 roles of up to 64 characters each. While the list is empty, the claim grants no role. |

Claim fields take a simple, top-level claim name such as `sub` or `roles`: letters, digits, and underscores, up to 64 characters. Nested paths such as `app.roles` aren't supported.

> [!WARNING]
>
> Roles from the token are only granted when runtime enforcement of token roles is enabled for your platform. That is a platform-side switch, off by default. Until it is enabled, the **Roles Claim** grants no role, even when the provider and **Allowed Roles** are configured correctly. Ask your Archie administrator whether it's enabled in your environment before you rely on it.

> [!NOTE]
>
> The **Roles Claim** is off by default. Leave it off unless your backend controls the custom claims. Turning it on isn't enough to grant roles: list the roles you want to accept in **Allowed Roles**. Roles still come from [Role-Based Access](https://archie.com/docs/backend/app-services/role-based-access.md).

Some operations aren't available yet to credentials whose roles come from the token. CSV import (`uploadCsv`) is refused with `403` and the code `CLAIMED_ROLES_OPERATION_UNSUPPORTED`. Run imports with a credential whose roles are assigned in Archie.

Archie checks **Allowed Roles** when you save the provider, and checks every role again on each request. A role that has since become administrative or privileged, been deactivated, or been deleted is no longer granted, even if it is still in **Allowed Roles**. If Archie can't check the roles at that moment, the request is refused with `503` and a `Retry-After` header. It is never let through with unchecked roles.

## Test a token before you save

Use **Test token** to check your configuration without saving it.

1. Get a fresh ID token from your app, for example by logging the result of `getIdToken()` in a development build.
2. Click **Test token** and paste the token.
3. Read the result. If the token is rejected, compare the result with the [error codes](#error-codes).

The test uses the values currently in the form, including unsaved changes. The token is never stored.

You can run up to 10 tests per minute per project. Beyond that, the test is refused with the code `rate_limited`. Wait a minute and try again. `rate_limited` only comes from **Test token**; it is never the answer to a request from your app.

## What Archie checks when you save

Besides validating each field, Archie runs these checks when you create a Firebase provider or save a change to its configuration (saving an unchanged configuration skips them):

* **Google's signing keys.** Archie downloads Google's public `securetoken` keys. If the download fails, the provider is still saved and the console shows a warning.
* **The service account, with Check Revoked Tokens on.** Archie asks Google to read the project's users with the key. First Archie exchanges the key for an access token. If Google's token endpoint rejects the key with any `4xx` answer, including `429`, the save is blocked: for example, the key was revoked or deleted. Any other failure of that exchange, such as a `5xx` answer or Google being unreachable, saves the provider with a warning. Then Archie reads the project's users. If that call answers `403`, the save is blocked: the service account doesn't have the **Firebase Authentication Viewer** role. A `429` or `5xx` answer, or Google being unreachable, saves the provider with a warning. Any other answer that isn't `200` blocks the save.

> [!WARNING]
>
> An ID token is a credential until it expires. Don't paste real user tokens into tickets, chats, or logs.

## Set up the service account for revocation

Archie needs a service account to ask Google about a user's status. Give it the least access possible.

**1. Create the service account**

In the [Google Cloud console](https://console.cloud.google.com/), select the same project as your Firebase Project ID. Navigate to **IAM & Admin → Service Accounts** and click **Create service account**. Give it a name such as `archie-token-revocation`.

**2. Grant the minimum role**

Grant the role **Firebase Authentication Viewer**. Archie doesn't need any other role.

**3. Create a JSON key**

Open the service account, go to the **Keys** tab, and click **Add key → Create new key**. Choose **JSON** and click **Create**. Your browser downloads the key file.

**4. Paste the key into Archie**

Turn on **Check Revoked Tokens**, paste the full content of the JSON file into **Service Account Key**, and click **Save**. Then delete the downloaded file from your computer.

The key file has this shape. Never commit a real key to source control.

```json theme={null}
{
  "type": "service_account",
  "project_id": "your-firebase-project-id",
  "private_key_id": "<private-key-id>",
  "private_key": "-----BEGIN PRIVATE KEY-----\n<redacted>\n-----END PRIVATE KEY-----\n",
  "client_email": "archie-token-revocation@your-firebase-project-id.iam.gserviceaccount.com",
  "client_id": "<client-id>"
}
```

> [!NOTE]
>
> If your organization blocks service account key creation, ask your Google Cloud administrator for an exception for this service account.

### Rotate the key without downtime

1. Create a new JSON key for the same service account.
2. Paste the new key into **Service Account Key** and click **Save**.
3. Check that requests still succeed.
4. Delete the old key in the Google Cloud console.

The old key keeps working until you delete it, so requests never fail during the switch.

## How long changes take

Archie caches some results to keep requests fast. These are the windows to plan for.

| Event | When it takes effect |
| - | - |
| ID token expiry | Firebase ID tokens live for 1 hour. |
| Revocation status | Cached for up to 5 minutes. |
| User revoked or disabled in Firebase, with **Check Revoked Tokens** on | The user may still get in for up to about 6.5 minutes: up to 5 minutes for the revocation status, plus up to 60 seconds and 30 seconds of other cached results. |
| User revoked or disabled in Firebase, with **Check Revoked Tokens** off | Not detected. The token works until it expires. |
| Provider disabled or edited | Usually within a few seconds. At most about 90 seconds. |

> [!NOTE]
>
> When you disable or edit the provider, Archie clears the cached results of that project. If that notification is lost, the cached results expire on their own within about 90 seconds.

## Error codes

When Archie rejects a token, it answers HTTP `401` with this header and body:

```http theme={null}
WWW-Authenticate: Bearer error="invalid_token"
```

```json theme={null}
{
  "errors": [
    {
      "message": "Invalid credentials",
      "extensions": { "code": "token_expired" }
    }
  ]
}
```

Read `extensions.code` to find the cause. The message is always the same.

| Code | Meaning |
| - | - |
| `token_missing` | The `Authorization` header is `Bearer` with an empty token. A request with no `Authorization` header gets a `401` without a code (see [How requests work](#how-requests-work)). |
| `token_malformed` | The token is not a well-formed JWT, or it lacks one of the required time claims: `exp`, `iat`, or `auth_time`. |
| `token_invalid_header` | The token header is not accepted. Only `RS256` tokens with a `kid` are accepted. |
| `token_unknown_key` | The `kid` doesn't match any of Google's current public keys. |
| `token_invalid_signature` | The signature doesn't verify. |
| `token_expired` | The token has expired. Get a fresh one with `getIdToken()`. |
| `token_not_yet_valid` | The token's times are in the future, beyond the allowed **Clock Skew**. |
| `token_invalid_audience` | The token was issued for another project. Firebase custom tokens also land here. |
| `token_invalid_issuer` | The issuer is not `https://securetoken.google.com/<projectId>`. Google Sign-In ID tokens also land here. |
| `token_invalid_subject` | The `sub` claim is missing or invalid. |
| `token_invalid_tenant` | The token's tenant doesn't match the configured **Tenant ID**, or the token carries a tenant and the provider has no **Tenant ID**. |
| `token_policy_rejected` | The token breaks one of your restrictions. The reason is not disclosed. |
| `token_revoked` | The user's tokens were revoked after this token was issued. |
| `user_disabled` | The user's account is disabled in Firebase. |

When **Check Revoked Tokens** is on and Archie can't reach Google, the request is refused, never accepted. The answer is `503` with a `Retry-After` header and the code `AUTH_UNAVAILABLE`, or `401` in some deployments. Retry after the indicated time.

> [!NOTE]
>
> `token_policy_rejected` doesn't say which restriction failed, so attackers can't probe your policy. To find the cause, review the **Restrictions** section one field at a time and use **Test token** after each change.

## Not supported

* **Firebase custom tokens.** Exchange them in your app with `signInWithCustomToken()` and send the resulting ID token.
* **Firebase session cookies.**
* **App Check tokens.**
* **The Firebase Auth Emulator** in deployed environments. Emulator tokens aren't signed by Google.

## FAQ

> [accordion] Can I send a Google Sign-In token directly?
>
> No. Google Sign-In ID tokens are issued by Google accounts, not by your Firebase project, so they fail with `token_invalid_issuer`. Sign the user in to Firebase with the Google credential, then send the Firebase ID token.

> [accordion] Does Archie call Google on every request?
>
> No. Signatures are checked locally with Google's public keys. Archie only calls Google for revocation status when **Check Revoked Tokens** is on, and it caches the answer for up to 5 minutes.

> [accordion] Why are my phone sign-in users rejected?
>
> In this version, every token must include an email. Phone and anonymous sign-in tokens have none, so they're rejected with `token_policy_rejected`.

> [accordion] Why are my Identity Platform users rejected with token\_invalid\_tenant?
>
> Their tokens carry an Identity Platform tenant. If the provider has no **Tenant ID**, every token with a tenant is rejected; if it has one, only tokens from that tenant are accepted. Set **Tenant ID** to the tenant your users sign in to.

> [accordion] Can I accept tokens from more than one Firebase project?
>
> Yes. Add up to 10 other projects to **Additional Project IDs**. This can't be combined with **Check Revoked Tokens**: revocation is only checked in the main project, so a configuration with both is rejected.

> [accordion] Do I configure the provider in every environment?
>
> Yes. Authentication providers are scoped per environment and their secrets are never copied when you branch an environment. See [Authentication Providers](https://archie.com/docs/backend/app-services/authentication-providers.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.