skip to content

Firebase Authentication

Firebase Authentication: providers, anonymous accounts, custom tokens and claims, and an ID token that expires hourly and refreshes. The interview question is verifying that token server-side.

on this pageshow

explore

questions

6

In Firebase Authentication, how long does an ID token live, what ends its refresh token, and when should an Android app force a refresh?

level: middleimportance: must knowfreq 68%

answer

  1. two tokens, two lifetimes
  2. short JWT, long-lived refresh
  3. deleted, disabled, major change, revoked
  4. getIdToken(false) vs getIdToken(true)

basics

~20 s

A Firebase ID token lasts one hour; the long-lived refresh token mints new ones until the user is deleted, disabled, changes password or email, or is revoked. Call getIdToken(true) only when server-side state such as custom claims changed.

solid answer

~40 s

Sign-in exchanges the user's credentials for a short-lived **ID token** (a signed JWT, valid for one hour) and a long-lived **refresh token**. The Android SDK persists both and uses the refresh token to mint new ID tokens, so the session outlives any single token. Refresh tokens have no timer: they stop working when the user is deleted or disabled, after a major account change such as a password or email update, or when a backend calls the Admin SDK's `revokeRefreshTokens`. Before each call to your own backend, take `getIdToken(false)`, which returns the cached token while it is valid and refreshes it otherwise, and send the token, never the bare `uid`. Force a refresh with `getIdToken(true)` only when you know the token's contents changed, typically right after your backend set new custom claims.

code

kotlin · 10 lines
kotlin
import com.google.firebase.Firebase
import com.google.firebase.auth.auth

// Hands the caller a current ID token for an Authorization: Bearer header.
fun withIdToken(forceRefresh: Boolean = false, onToken: (String?) -> Unit) {
    val user = Firebase.auth.currentUser ?: return onToken(null)
    user.getIdToken(forceRefresh)
        .addOnSuccessListener { result -> onToken(result.token) }
        .addOnFailureListener { onToken(null) } // e.g. the account was deleted or disabled elsewhere
}

go deeper

for a junior

Recall the two tokens: an ID token that lasts an hour and a refresh token that keeps the session alive, and that the backend gets the ID token, not the uid.

for a middle

Explain what getIdToken(false) and getIdToken(true) each do, list what ends a refresh token, and say why auth_time stays fixed across refreshes.

for a senior

Diagnose the stale-session cases: a non-null currentUser whose account was deleted elsewhere, a token cached past its hour, and recent-login failures that a refresh cannot fix.

for a principal

Decide how long a stolen-but-unexpired ID token may be tolerated per endpoint, and whether the revocation check's extra round trip is worth it for sensitive calls.

## Two tokens, two lifetimes When a user signs in, with a password, a federated provider, anonymously or with a custom token, the Firebase Authentication backend exchanges the credentials for two tokens: - an **ID token**, a signed JWT that identifies the user to Firebase services and to your own backend. It is **short-lived: one hour**. - a **refresh token**, long-lived, which the client SDK uses to obtain new ID tokens without asking the user for anything. The Android SDK keeps both and persists the signed-in user, which is why someone stays signed in across app restarts for weeks: the session lasts as long as the refresh token does, not as long as any one ID token. Each refreshed ID token has a new `iat` (issued-at) but the same `auth_time`, the moment the user actually signed in to this session. ## What ends the refresh token Refresh tokens do not expire on a schedule. Firebase documents that they stop working when: 1. the user is **deleted**; 2. the user is **disabled**; 3. a **major account change** is detected, such as a password or email address update (a password reset revokes the old tokens automatically); 4. a backend explicitly revokes them with the Admin SDK's `revokeRefreshTokens(uid)`. Signing out on one device clears that device's local state; it does not revoke the user's sessions on other devices. ## Getting a token on Android `FirebaseUser.getIdToken(forceRefresh)` returns a `Task<GetTokenResult>`; `result.token` is the JWT string and `result.claims` its decoded claims. - `getIdToken(false)` returns the cached ID token while it is still valid and uses the refresh token to fetch a new one when it is not. This is the call to make right before each request to your backend. - `getIdToken(true)` goes to the network for a new ID token every time. Use it when you know the server-side state behind the token changed, typically after your backend set new custom claims, not on every request, where it only adds a round trip. Firebase's own client SDKs (Firestore, Cloud Storage, callable functions) attach and refresh the token themselves; you handle it only for your own backend. ## What to send to your backend Send the **ID token**, in an `Authorization: Bearer` header over HTTPS, and let the server verify it. Do not send the `uid` alone: Firebase's documentation says explicitly not to use it to authenticate with a backend, because anyone can type a `uid` while only Firebase can sign a token. The server takes the `uid` from the verified token. ## Edge cases the SDK documents | Situation | What `currentUser` shows | What actually holds | |---|---|---| | Auth still initialising at launch | may be `null` | the user may still be signed in | | User deleted on another device, local token not yet refreshed | non-null | authenticated calls fail; the next refresh fails | | User signed out on this device | `null` | other devices keep their sessions | The documentation recommends attaching an `AuthStateListener`, which is called when the underlying token state changes, instead of reading `currentUser` once in `onStart` and trusting it. ## Mistakes that look like Firebase bugs - **Caching the token string yourself** in a singleton or in preferences. It goes stale after an hour and the backend starts answering 401; ask `getIdToken(false)` each time instead, since the SDK already caches it properly. - **Forcing a refresh on every request.** `getIdToken(true)` makes every call wait for an extra network round trip and buys nothing when nothing changed. - **Treating a 401 from your backend as a network blip** and retrying with the same token. Fetch a token again first; if that fails, the session has ended and the user must sign in. - **Assuming one sign-out ends every session.** It ends this device's; ending them all is a backend decision. ## Re-authentication is a different requirement Some actions (deleting the account, setting a new email address or password) require that the user **signed in recently**, however fresh the ID token is. When the sign-in is too old the call throws `FirebaseAuthRecentLoginRequiredException`; collect the credentials again and call `reauthenticate(credential)`. A forced token refresh is not a substitute: the requirement is about when the user last proved who they are, and a refreshed token keeps the same `auth_time`.

  • A backend rejects an Android client's Firebase ID token as expired in the middle of a long session. What do you change on the client?
    Stop caching the token string yourself. Call `getIdToken(false)` immediately before each request so the SDK hands back a valid token, refreshing it when the cached one has expired. If a request still gets an expired-token 401, fetch a token again and retry that request once; a second failure means the session itself has ended.
  • Does signing out of a Firebase app on one phone end the same user's session on their tablet?
    No. Signing out clears the current user and its tokens on that device only; the tablet's refresh token keeps working. To end every session, the backend calls `revokeRefreshTokens(uid)`, or an event that revokes tokens happens, such as a password reset.
  • What does getIdToken(false) do once the user's Firebase refresh token has been revoked?
    While the cached ID token is unexpired it may still be returned, because nothing on the device knows about the revocation yet. Once a refresh is needed, the refresh token is rejected, the task fails, and the user is signed out and must sign in again; a backend using the revocation check rejects the old token sooner.

  • The ID token stays valid for as long as the user is signed in.
  • Call getIdToken(true) before every backend request to be safe.
  • Send the uid to the backend; it is unique, so it identifies the user.
  • A non-null currentUser proves the session is still valid on the server.
  • Signing out on one device ends the user's sessions everywhere.
open as a page

How does a backend verify a Firebase ID token with the Admin SDK's verifyIdToken, and what does that call not check?

level: middleimportance: must knowfreq 70%

basics

~20 s

The Admin SDK's verifyIdToken checks the RS256 signature against Google's public keys, the expiry and issue times, and that aud and iss name your project, then returns the uid and claims. It skips revocation and disabled-user checks unless checkRevoked is true.

open as a page

In Firebase Authentication on Android, what is an anonymous account, and how do you upgrade a guest to Google sign-in without losing their data?

level: juniorimportance: should knowfreq 55%

basics

~20 s

An anonymous account is a real Firebase user with a uid but no sign-in credential, created by signInAnonymously. To upgrade, pass the Google credential to the current user's linkWithCredential, which attaches it and keeps the same uid.

open as a page

After your backend sets a Firebase Authentication custom claim with setCustomUserClaims, why does the Android app not see it, and how do you fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Custom claims travel inside the ID token, and the token on the phone was issued before the change. They appear only in the next token: at sign-in, at the hourly refresh, or when the app calls getIdToken(true) after the backend confirms.

open as a page

With the Firebase Admin SDK, how do you cut off a stolen phone's session in a notes app, and why might its calls still succeed?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Call revokeRefreshTokens(uid) so no device can mint new ID tokens. ID tokens already issued stay valid for up to an hour, so endpoints that must refuse them at once verify with verifyIdToken(idToken, true).

open as a page

How do Firebase Authentication custom tokens let users of an existing login system sign in to Firebase from an Android app?

level: middleimportance: nice to knowfreq 28%

basics

~10 s

Your 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.

open as a page