How do Firebase Authentication custom tokens let users of an existing login system sign in to Firebase from an Android app?
answer
- your server vouches for the user
- createCustomToken(uid, claims)
- signInWithCustomToken on the device
- one hour to exchange, not to stay
- signBlob and the service account
basics
~10 sYour server validates the user with its own system, then mints a signed JWT with the Admin SDK's createCustomToken(uid). The app exchanges it with signInWithCustomToken and gets an ordinary Firebase session for that uid.
solid answer
~40 sThe app sends the user's credentials to your own login endpoint; after checking them, the server calls `getAuth().createCustomToken(uid, developerClaims)` with a stable `uid` of 1 to 128 characters and returns the token. The app calls `signInWithCustomToken(token)`; Firebase creates the user if that `uid` is new, and from then on it is a normal session with hourly ID tokens and a refresh token. The custom token's one-hour expiry limits only the exchange, not how long the user stays signed in. Tokens are signed with a Google service account's key: locally from a key file, or remotely through IAM, which needs `iam.serviceAccounts.signBlob`. Never mint them on the device, and do not verify them with `verifyIdToken`, which accepts only ID tokens.
code
typescript · 7 linesimport { getAuth } from "firebase-admin/auth";
// Runs after your own system has accepted the user's credentials.
export async function firebaseTokenFor(accountId: string, plan: string): Promise<string> {
const uid = `acct:${accountId}`; // stable, 1-128 characters
return getAuth().createCustomToken(uid, { plan }); // expires one hour after issue
}go deeper
Know that a custom token is minted by your server after its own login check and exchanged on the device with signInWithCustomToken.
Explain the flow end to end, what the one-hour expiry limits, and why the uid must be stable and at most 128 characters.
Diagnose signing failures (signBlob permission, IAM API, no service account found), keep keys off the device, and know that custom-token claims override claims set with setCustomUserClaims.
Judge whether to keep an existing identity system behind custom tokens or migrate users into Firebase providers, weighing two systems to run against a risky migration.
## When you need custom tokens Firebase Authentication's built-in providers cover email and password, phone, anonymous and federated sign-in. An app that already has its **own account system** (a company directory, a legacy user database) can keep it and still give users a Firebase identity, so that Firestore, Cloud Storage and Security Rules work as usual. The bridge is a **custom token**: a JWT your server mints after checking the user by its own rules, which the client trades for a normal Firebase session. Custom tokens are not custom claims. Claims decorate users who signed in with any provider; a custom token is itself a way to sign in. ## The flow 1. The Android app sends the user's credentials to **your** login endpoint, which validates them however it always has. 2. The server calls `getAuth().createCustomToken(uid, developerClaims)`. The `uid` is a string of 1 to 128 characters that stably identifies the user; derive it from your own user id, never from something that can change. 3. The server returns the token to the app over HTTPS. 4. The app calls `Firebase.auth.signInWithCustomToken(token)`. If no Firebase user has that `uid`, one is created. 5. The user now has an ordinary Firebase session: hourly **ID tokens** whose `sub` is your `uid`, a long-lived **refresh token**, and `firebase.sign_in_provider` equal to `custom` in rules. The new user's profile starts empty; if you want a display name or email on the Firebase user, your system has to set them. ## What the one-hour expiry means A token from `createCustomToken` expires **one hour** after it is issued, and a token minted by hand may set `exp` at most 3600 seconds after `iat`. That limit applies only to the **exchange**: once `signInWithCustomToken` succeeds, the user stays signed in until the session ends in the usual ways (sign-out, deletion, disabling, revocation). Do not build an hourly re-login loop around it. ## Signing: the part that fails in production A custom token is signed with a **Google service account's private key**. The Admin SDK can get there three ways: | Setup | How it signs | What goes wrong | |---|---|---| | A service account JSON key file | locally, with no API call | the key file leaks, for example into version control | | Application default credentials on Google infrastructure | discovers the default service account and signs remotely through IAM (App Engine standard uses its App Identity service instead) | the account lacks `iam.serviceAccounts.signBlob`, or the IAM API is disabled | | The `serviceAccountId` option | signs remotely as that account | the same permission requirement | The usual failure is a deploy where the default service account (on 2nd-gen Cloud Functions, the default Compute Engine service account) lacks `iam.serviceAccounts.signBlob`. The fix is to grant it the **Service Account Token Creator** role. A "Failed to determine service account" error means the SDK found no key file, no `serviceAccountId` and no metadata server to ask. Never put a service account key in the Android app to mint tokens on the device: anyone who unpacks the APK could then sign in as any `uid`. ## Treat the custom token as a credential For the hour it lives, a custom token is a bearer credential: whoever holds it can call `signInWithCustomToken` and become that `uid`. So: - mint it only after your own login check has fully passed, including any second factor your system enforces; - return it over HTTPS in the login response and keep it out of logs, analytics events and crash reports; - have the app exchange it at once and discard it, instead of storing it for later; - let the Firebase session, not the custom token, carry the user from then on. ## Claims and interactions - **Developer claims** passed to `createCustomToken` appear in the ID tokens issued for that sign-in, and in `request.auth.token` in rules. They cannot use reserved JWT names such as `aud`, `exp` or `iat`. - Where a custom-token claim and a claim set with `setCustomUserClaims` share a key, the **custom-token claim wins**. - `verifyIdToken` rejects custom tokens: it verifies ID tokens from the client SDKs. Your API should accept only the ID token the app holds after signing in. - A hand-minted token, for a backend language without an Admin SDK, must use `RS256`, set `iss` and `sub` to the service account's email, and set `aud` to the Identity Toolkit URL that Firebase documents.
- Users who sign in to Firebase with custom tokens now want Google sign-in too. How do you add it without creating second accounts?While the user is signed in through the custom token, link the Google credential to that same account with `linkWithCredential`; the `uid` your server chose stays, and the user can later sign in with either method. If that Google account already has its own Firebase user, linking fails with `ERROR_CREDENTIAL_ALREADY_IN_USE` and you must merge.
- Your legacy system renames user ids during a migration. Why does that matter for Firebase custom tokens?The `uid` in the custom token is the Firebase user's identity, and data and rules are keyed by it. If the next token carries a different `uid`, Firebase signs the person in to a brand-new user and their data stays under the old one. Keep a stable mapping, or migrate the data along with the id.
- The user is signed out when the custom token expires after an hour.
- The Android app can mint its own custom token if it ships the service account key.
- Verify the custom token on your backend with verifyIdToken.
- createCustomToken works anywhere without a service account or signing permission.
- Claims set with setCustomUserClaims always override a custom token's claims.