Join our Newsletter — 33% off our NHI Course
Home› Guides› Firebase Credentials Security Guide: API Keys, Service Accounts…
Guide Non-Human Identity (NHI)

Firebase Credentials Security Guide: API Keys, Service Accounts and Security Rules

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 26 October 2026 15 min read
On this page

Firebase mixes credentials that are meant to be public with credentials that hold full administrative power, and most Firebase incidents come from confusing the two. The web API key in a Firebase config object is an identifier that ships in every client, while the Admin SDK service account key can read and write every database, bucket and user record in the project. Between them sit Security Rules, which are the real access control for client traffic and are often left open. This guide explains how identity and access work in Firebase, which credentials need protecting and how, what to log, and a hardening baseline for each layer. It is written for application security engineers, cloud platform teams and developers who own Firebase projects in production.

Key takeaways

  • Firebase API keys are identifiers, not secrets. Firebase documents them as public by design; protection comes from Security Rules, App Check and IAM, but every key still needs API restrictions so it cannot call billable or sensitive APIs.
  • Security Rules are the access control for client traffic. Rules such as allow read, write: if true; or if request.auth != null; expose the whole database to anyone who knows the project ID or can create an account.
  • The Admin SDK service account key is the crown jewel. It authenticates server code with full admin privileges and is not constrained by Security Rules; prefer attached service accounts and Application Default Credentials so no key file exists.
  • A Firebase project is a Google Cloud project. IAM roles, service accounts, organisation policies and audit logs all come from Google Cloud, so harden it as a cloud project, not just an app backend.
  • Enabling a new API can change what an old key can do. Unrestricted Google API keys silently gained Gemini access when the Generative Language API was enabled, so keep AI keys separate and restricted.

How identity and access work in Firebase

Firebase has three separate access paths, and each is governed by a different control. Treating them as one is the root of most misconfigurations.

PathWho uses itCredentialWhat enforces access
Client SDKs (web, Android, iOS)End users of your appFirebase config (API key, project ID, database URL, bucket name) plus a Firebase Authentication ID tokenSecurity Rules for Cloud Firestore, Realtime Database and Cloud Storage; App Check where enforced
Admin SDK and server APIsYour backend, Cloud Functions, scripts, CI jobsGoogle Cloud service account (attached identity or JSON private key)Google Cloud IAM roles on the service account; Security Rules do not apply
Console, CLI and management APIsDevelopers and administratorsGoogle accounts, groups and service accountsIAM basic roles (Owner, Editor, Viewer), Firebase predefined roles and custom roles
  • The config object is public: Firebase states that the config file or object content is considered public. It contains the API key, project ID, Realtime Database URL and Cloud Storage bucket name. Hiding it adds nothing; rules and IAM must carry the load.
  • The project ID is guessable: it appears in public resource names such as default Hosting subdomains, the default Realtime Database URL and the default bucket name, and it cannot be changed once resources are provisioned. Assume attackers know it.
  • Authentication is not authorisation: Firebase Authentication proves who the user is and issues an ID token. Whether that user may read a document is decided only by Security Rules (client path) or by your own server code (Admin path).
  • App Check is a third signal: it attests that a request comes from your genuine app on a genuine device (Play Integrity, App Attest, DeviceCheck, reCAPTCHA Enterprise or reCAPTCHA v3) and rejects requests without a valid attestation once enforcement is on. It does not replace user authentication or rules.

See the Google Cloud IAM and Service Accounts Guide for the underlying IAM model.

Admin roles and privileged access

Because project members are Google Cloud principals, access granted in the Firebase console applies across Google Cloud and the reverse. Firebase does not list service accounts in its own console; you have to review them on the Google Cloud IAM page.

RoleWhat it grantsGuidance
Owner (basic)Everything in the Google Cloud project, including IAM policy changesTwo named break-glass holders at most; never a shared mailbox or a CI identity
Editor (basic)Broad write access to most resources across the projectAvoid for people and service accounts; replace with Firebase or product roles
Firebase Admin (roles/firebase.admin)Read and write on all Firebase products, plus firebase.projects.update, firebase.projects.delete and Extensions managementPlatform owners only; treat as privileged
Firebase Viewer (roles/firebase.viewer)Read-only access to all Firebase productsDefault for most engineers and support staff
Product-category and product-level roles (for example roles/firebase.developAdmin)Read and write or read-only on a group of products or one productUse these for teams that own one product such as Firestore or Hosting
Custom rolesA tailored permission set, managed in the Google Cloud consoleUse when a deploy pipeline needs only rules and Hosting deployment
  • Who changes IAM: only Owners or principals with resourcemanager.projects.setIamPolicy can manage roles. Keep that permission off CI identities.
  • Rules deployment is a privileged action: anyone who can deploy Security Rules can open the whole database. The CLI command firebase deploy --only firestore:rules overwrites whatever rules are live in the console, so restrict who and what can run it to the release pipeline.
  • Extensions run with their own service accounts: installing one is a Firebase Admin action, and its permissions should be reviewed like any third-party integration.
  • Organisation-managed projects: projects under a Google Cloud organisation may have no Owner, in which case the organisation administrator assigns one. That is a good default: it puts project ownership behind central governance.

See the Service Account Security Guide.

Integrations, API tokens and service accounts

API keys

  • Restrict every key: Firebase-provisioned keys are automatically restricted to Firebase-related APIs, and unrestricted keys that Firebase auto-created before May 2024 were restricted to Firebase APIs plus the project's enabled APIs. Check keys created by hand in the Google Cloud console: they may still be unrestricted.
  • Keep the allowlist short: most Firebase APIs do not need to be on a key's allowlist. Client-facing ones that do include identitytoolkit.googleapis.com (Authentication), firestore.googleapis.com, firebasedatabase.googleapis.com, firebasestorage.googleapis.com, firebaseappcheck.googleapis.com and firebasevertexai.googleapis.com (Firebase AI Logic). Remove only what you have tested, because removing a needed API breaks sign-in or data access.
  • Separate keys for other Google APIs: Firebase recommends separate, restricted keys for any non-Firebase Google Cloud API, especially billable ones, so you can rotate them without disturbing the app.
  • Never put a Gemini key in the client: Firebase states the Gemini Developer API key should never be included in code or configuration files, should be restricted to the Generative Language API and should never be added to the allowlist of a public key. Use Firebase AI Logic with App Check, or call Gemini from your server. The Google API Keys Exposure 2026 research found 2,863 live public keys that had quietly gained Gemini access once the API was enabled on their projects. See the LLMjacking Guide.
  • Cap abuse with quotas: a leaked key cannot reach data protected by rules, but it can still hit authentication endpoints. Firebase suggests tightening the default quota for identitytoolkit.googleapis.com to slow brute force, while leaving headroom for growth. Test any new restriction or limit on a test key first.

Service account keys and the Admin SDK

  • Prefer no key at all: in Google environments such as Cloud Run, App Engine and Cloud Functions for Firebase, Firebase strongly recommends initialising the Admin SDK with Application Default Credentials, which uses the attached service account. No JSON file is created, so none can leak.
  • Outside Google Cloud, federate: for CI systems, other clouds and on-premises servers, use Workload Identity Federation instead of downloading a key. See the Workload Identity Federation Guide.
  • If a key is unavoidable: the console's Settings, Service accounts, Generate New Private Key flow creates a JSON key with no expiry by default. Firebase's own setup page warns that extremely high security awareness is required. Load it through GOOGLE_APPLICATION_CREDENTIALS from a secrets manager, never from the repository, and give the service account a narrow custom role rather than Editor.
  • Block keys by policy: enforce the organisation policy constraints iam.managed.disableServiceAccountKeyCreation and iam.managed.disableServiceAccountKeyUpload (legacy forms iam.disableServiceAccountKeyCreation and iam.disableServiceAccountKeyUpload) at the organisation root, with project exceptions only where justified. Google enforces these by default for organisations created on or after 3 May 2024. Set iam.serviceAccountKeyExposureResponse to DISABLE_KEY so Google disables keys it detects as leaked publicly, and use iam.serviceAccountKeyExpiryHours for non-production keys. See the Google Cloud Organization Policy Guide.

Secrets used by Cloud Functions

  • Use defineSecret(): it stores values in Cloud Secret Manager, binds each secret only to the functions that list it in their secrets option and exposes the value at runtime through .value(). Third-party API keys (payments, email, LLM providers) belong here, not in .env files.
  • Migrate off functions.config(): it was deprecated in firebase-functions 6.0.0, and Firebase states new deployments that use it will fail after March 2027.

See the Cloud Secrets Managers Guide.

Security Rules: the control that decides exposure

PatternExample conditionExposureReplace with
Open accessFirestore allow read, write: if true;; Realtime Database ".read": true, ".write": true; Storage allow read, write;Anyone who knows the project ID can read, change or delete all dataPath-specific rules tied to the authenticated user
Any authenticated userif request.auth != null; or "auth.uid !== null" on the rootAnyone who self-registers through Firebase Authentication gets the whole databaseOwner checks such as request.auth.uid == resource.data.author_uid
Test-mode rules left in placeTime-limited open rules from project setupOpen until someone notices, or until the expiry date breaks the app and is extendedProduction rules written and tested before launch
Mixed access without write checksPublic read with unchecked writesData tampering and storage abusePublic read, owner-only create, update and delete
Role checks without a trusted sourceRole read from a field the user can editPrivilege escalation by self-assignmentRoles from custom claims or a document only the Admin SDK can write
  • Write rules per path: start from deny by default and open only the documents a user owns or a group may see. For Storage, scope to user paths such as match /user/{userId}/{fileName}.
  • Test rules like code: the Local Emulator Suite checks rules syntactically and semantically, and unit tests against the Firestore and Realtime Database emulators should run in CI on every rules change. Firebase advises against updating rules through the Admin SDK without that testing.
  • Remember the cost of lookups: role-based rules that use get() or exists() incur document reads, which is a reason to put roles in custom claims where practical.

The Firebase Misconfigurations 2024 research showed the scale of the problem: 916 websites with open Firebase back ends exposed about 125 million user records, including 19 million plaintext passwords.

Logging and detection

Firebase logging comes from Google Cloud Audit Logs. Admin Activity logs record configuration changes; Data Access logs record reads and writes and must be enabled deliberately.

SignalSourceWhat to look for
Service account key created or uploadedIAM Admin Activity audit logsAny new key in a production project; keys created outside the approved exception list
Key last usedService account insights and key authentication eventsKeys unused for 90 days (delete them); keys used from unexpected IP ranges
IAM policy changesAdmin Activity (SetIamPolicy)Owner, Editor or roles/firebase.admin granted to a new principal
Firestore data accessData Access logs for datastore.googleapis.com (covers firestore.googleapis.com)Bulk RunQuery, Listen or Commit volume; caller in AuthenticationInfo and requestMetadata.callerIp
Firestore admin operationsAdmin Activity (ExportDocuments, CreateDatabase)Exports not run by the backup job
Rules releasesFirebase console release history and deploy pipeline logsRules deployed outside the pipeline or by a person
API key usageAPI metrics per key in Google CloudCalls to APIs outside the key's purpose; spikes on identitytoolkit.googleapis.com

Note that individual writes from imports, bulk deletes and TTL are not audit logged, and that Data Access logging adds cost, so enable it first for production databases holding personal data.

Metrics that show it is working

  • User-managed service account keys: number in production projects, target zero, with an owner and expiry for every exception.
  • Unrestricted API keys: count across all projects, target zero.
  • Rules coverage: percentage of rules files with emulator unit tests in CI.
  • Rules drift: rules releases not originating from the pipeline, target zero.
  • App Check enforcement: share of supported products (Firestore, Realtime Database, Storage, callable functions, AI Logic) with enforcement on.
  • Privileged principals: number of Owner, Editor and Firebase Admin grants per project, reviewed quarterly.

Hardening baseline

  1. Inventory first: list every Firebase project, its environment, its API keys and their restrictions, its service accounts and their keys, and which APIs are enabled (look for the Generative Language API in particular).
  2. Separate environments: use separate projects for development, staging and production so test keys, test users and relaxed rules never touch production data.
  3. Close the rules: replace open and any-authenticated-user rules, add emulator tests, and move rules deployment into the release pipeline with review.
  4. Restrict keys: apply API restrictions and, where the platform supports it, application restrictions to every key; split non-Firebase and AI keys into their own restricted keys; test on a test key before changing production.
  5. Remove key files: move server code to attached service accounts or Workload Identity Federation, delete the JSON keys, then enforce the key creation and upload constraints.
  6. Turn on App Check in monitor mode: review request metrics until legitimate traffic is attested, then enforce product by product. Keep debug provider tokens out of production builds.
  7. Enable logging: Data Access logs on production databases, alerts on key creation and privileged IAM grants, budget alerts on the billing account.
  8. Roll back safely: keep the previous rules file in version control so a rules release that breaks the app can be redeployed in minutes; never respond to breakage by reopening rules.

Small team or large estate

  • Small teams: one organisation, separate projects per environment, ADC everywhere, the key-creation constraint on, and rules tests in the same repository as the app. This covers the bulk of the risk.
  • Large estates: folders per business unit, organisation policies inherited from the root, a central inventory of keys and service accounts, custom deployer roles, and log export to the SOC. See the Google Cloud Security Guide.

Common misconfigurations

  • Open or any-user rules in production: the most common and most damaging Firebase failure, as the Firebase Misconfigurations 2024 case shows. Plaintext passwords stored in those databases made it worse.
  • Admin SDK key committed to a repository: deleting the file is not enough because version history keeps it. Delete the key in IAM immediately, then clean history and add secret scanning and pre-commit hooks. See the Secrets Scanning Buyer's Guide.
  • Treating the API key as the secret: teams obfuscate or rotate the public key while leaving rules open, which protects nothing.
  • Unrestricted keys plus newly enabled APIs: a key embedded years ago for Maps or Firebase inherits any API later enabled in the project, including Gemini.
  • Editor on the default service accounts: broad legacy grants turn any compromised function or build into project-wide write access.
  • Client-side admin logic: privileged operations performed in the client because rules were relaxed to make them work, instead of moving them to a callable function using the Admin SDK.

Framework mapping

Control areaNIST SP 800-53 Rev 5NIST CSF 2.0MITRE ATT&CK (threat addressed)
Service account keys and API keysIA-5 Authenticator ManagementPR.AA-01T1552.001 Credentials In Files
IAM roles and rules least privilegeAC-6 Least Privilege, AC-2 Account ManagementPR.AA-05T1078.004 Cloud Accounts
Security Rules and data exposureCM-6 Configuration SettingsPR.DS-01T1530 Data from Cloud Storage
Key and quota abuseAC-6DE.CM-09T1496 Resource Hijacking
Audit loggingAU-2 Event Logging, AU-6 Audit Record ReviewPR.PS-04, DE.CM-03Detection for all of the above

Practitioner checklist

  • Inventory every Firebase project, API key, service account and key, and enabled API.
  • Replace any if true or root-level request.auth != null rule with owner or role checks, and test rules in the emulator in CI.
  • Deploy rules only from the release pipeline; alert on any other release.
  • Apply API restrictions to every key and keep Gemini and other billable APIs on separate server-side credentials.
  • Run the Admin SDK with Application Default Credentials or Workload Identity Federation and delete JSON keys.
  • Enforce iam.managed.disableServiceAccountKeyCreation and set iam.serviceAccountKeyExposureResponse to DISABLE_KEY.
  • Remove Editor from people and default service accounts; use Firebase product roles and custom deployer roles.
  • Store function secrets with defineSecret() and migrate off functions.config() before March 2027.
  • Enable App Check in monitor mode, then enforce on Firestore, Realtime Database, Storage and AI Logic.
  • Enable Data Access audit logs on production databases and review privileged grants quarterly.

Standards and references

Related NHI Mgmt Group resources: API Key Management Guide · Google Cloud IAM and Service Accounts Guide · Workload Identity Federation Guide · Mobile App Security Guide · Vercel Tokens Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 26 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.