Avoid insecure rules

Use this guide to understand common vulnerabilities inFirebase Security Rulesconfigurations, review and better secure your own rules,and test your changes before deploying them.

If you receive an alert that your data isn't properly secured,review these commonly made errors and update any vulnerable rules.

Access yourFirebase Security Rules

To view your existingSecurity Rules, use either theFirebase CLI or theFirebase console. Make sure you edit your rules using the same method,consistently, to avoid mistakenly overwriting updates. If you're not surewhether your locally defined rules reflect the most recent updates, the Firebaseconsole always shows the most recently deployed version of yourFirebase Security Rules.

To access your rules from theFirebase console, select yourproject, then navigate toRealtime Database,Cloud Firestore orStorage. ClickRules once you're in the correct database or storagebucket.

To access your rules from theFirebase CLI, go to therules file noted in yourfirebase.json file.

UnderstandFirebase Security Rules

Firebase Security Rules protect your data from malicious users. When you create a databaseinstance orCloud Storage bucket in theFirebase console, you canchoose to either deny access to all users (Locked mode) or grant access toall users (Test mode). While you might want a more open configuration duringdevelopment, make sure you take the time to properly configure your rules andsecure your data before deploying your app.

As you're developing your app and testing different configurations for yourrules, use one of thelocal Firebase emulators to run your appin a local development environment.

Common scenarios with insecure rules

TheSecurity Rules you might have set up by default or as you initiallyworked on developing your app should be reviewed and updatedbefore you deploy your app. Make sure you properly secure your users' databy avoiding the following common pitfalls.

Open access

As you set up your Firebase project, you might have set your rules to allow openaccess during development. You might think you're the only person using yourapp, but if you've deployed it, it's available on the internet. If you're notauthenticating users and configuring security rules, then anyone who guessesyour project ID can steal, modify, or delete the data.

Not recommended: Read and write access for all users.

Cloud Firestore

// Allow read/write access to all users under any conditions// Warning:**NEVER** use this ruleset in production; it allows// anyone to overwrite your entire database.servicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:iftrue;}}}

Realtime Database

{//Allowread/writeaccesstoallusersunderanyconditions//Warning:**NEVER**usethisrulesetinproduction;itallows//anyonetooverwriteyourentiredatabase."rules":{".read":true,".write":true}}

Cloud Storage

//Anyonecanreadorwritetothebucket,evennon-usersofyourapp.//BecauseitissharedwithAppEngine,thiswillalsomake//filesuploadedusingAppEnginepublic.//Warning:ThisrulemakeseveryfileinyourCloudStoragebucketaccessibletoanyuser.//Applycautionbeforeusingitinproduction,sinceitmeansanyone//canoverwriteallyourfiles.servicefirebase.storage{match/b/{bucket}/o{match/{allPaths=**}{allowread,write;}}}
Solution: Rules that restrict read andwrite access.

Build rules that make sense for your data hierarchy. One of the common solutionsto this insecurity is user-based security withFirebase Authentication. Learn more aboutauthenticating users with rules.

Cloud Firestore

Content owner only

servicecloud.firestore{match/databases/{database}/documents{//Allowonlyauthenticatedcontentownersaccessmatch/some_collection/{document}{//Allowreadsanddeletionifthecurrentuserownstheexistingdocumentallowread,delete:ifrequest.auth.uid==resource.data.author_uid;//Allowcreationifthecurrentuserownsthenewdocumentallowcreate:ifrequest.auth.uid==request.resource.data.author_uid;//Allowupdatesbytheowner,andpreventchangeofownershipallowupdate:ifrequest.auth.uid==request.resource.data.author_uid&&request.auth.uid==resource.data.author_uid;}}}

Mixed public and private access

servicecloud.firestore{match/databases/{database}/documents{//Allowpublicreadaccess,butonlycontentownerscanwritematch/some_collection/{document}{//Allowpublicreadsallowread:iftrue//Allowcreationifthecurrentuserownsthenewdocumentallowcreate:ifrequest.auth.uid==request.resource.data.author_uid;//Allowupdatesbytheowner,andpreventchangeofownershipallowupdate:ifrequest.auth.uid==request.resource.data.author_uid&&request.auth.uid==resource.data.author_uid;//Allowdeletionifthecurrentuserownstheexistingdocumentallowdelete:ifrequest.auth.uid==resource.data.author_uid;}}}

Realtime Database

Content owner only

{  "rules": {    "some_path": {      "$uid": {        // Allow only authenticated content owners access to their data        ".read": "auth !== null && auth.uid === $uid",        ".write": "auth !== null && auth.uid === $uid"      }    }  }}

Mixed public and private access

{  // Allow anyone to read data, but only authenticated content owners can  // make changes to their data  "rules": {    "some_path/$uid": {      ".read": true,      // or ".read": "auth.uid !== null" for only authenticated users      ".write": "auth.uid === $uid"    }  }}

Cloud Storage

Content owner only

// Grants a user access to a node matching their user IDservicefirebase.storage{match/b/{bucket}/o{// Files look like: "user/<UID>/file.txt"match/user/{userId}/{fileName}{allowread,write:ifrequest.auth.uid==userId;}}}

Mixed public and private access

servicefirebase.storage{match/b/{bucket}/o{//Fileslooklike:"user/<UID>/file.txt"match/user/{userId}/{fileName}{allowread;allowwrite:ifrequest.auth.uid==userId;}}}

Access for any authenticated user

Sometimes,Security Rules check that a user is logged in, but don't furtherrestrict access based on that authentication. If one of your rules includesauth != null, confirm that you want any logged-in user to have access to thedata.

Not recommended: Any logged-in user has readand write access to your entire database.

Cloud Firestore

servicecloud.firestore{match/databases/{database}/documents{match/some_collection/{document}{allowread,write:ifrequest.auth.uid!=null;}}}

Realtime Database

{  "rules": {    ".read": "auth.uid !== null",    ".write": "auth.uid !== null"  }}

Cloud Storage

// Only authenticated users can read or write to the bucketservicefirebase.storage{match/b/{bucket}/o{match/{allPaths=**}{allowread,write:ifrequest.auth!=null;}}}
Solution: Narrow access using security conditions.

When you're checking for authentication, you might also want to use oneof the authentication properties to further restrict access to specific usersfor specific data sets. Learn more about the differentauthentication properties.

Cloud Firestore

Role-based access

servicecloud.firestore{match/databases/{database}/documents{//Assignrolestoallusersandrefineaccessbasedonuserrolesmatch/some_collection/{document}{allowread:ifget(/databases/$(database)/documents/users/$(request.auth.uid)).data.role=="Reader"allowwrite:ifget(/databases/$(database)/documents/users/$(request.auth.uid)).data.role=="Writer"//Note:Checkingforrolesinyourdatabaseusing`get`(asinthecode//above)or`exists`carrystandardchargesforreadoperations.}}}

Attribute-based access

// Give each user in your database a particular attribute// and set it to true/false// Then, use that attribute to grant access to subsets of data// For example, an "administrator" attribute set// to "true" grants write access to dataservicecloud.firestore{match/databases/{database}/documents{match/some_collection/{document}{allowwrite:ifget(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin==true;allowread:true;}}}

Mixed public and private access

service cloud.firestore {  match /databases/{database}/documents {    // Allow public read access, but only content owners can write    match /some_collection/{document} {      allow read: if true      allow write: if request.auth.uid == request.resource.data.author_uid    }  }}

Realtime Database

Content owner only

{  "rules": {    "some_path": {      "$uid": {        // Allow only authenticated content owners access to their data        ".read": "auth.uid === $uid",        ".write": "auth.uid === $uid"      }    }  }}

Path-delineated access

{  "rules": {    "some_path/$uid": {      ".write": "auth.uid === $uid",      // Create a "public" subpath in your dataset      "public": {        ".read": true        // or ".read": "auth.uid !== null"      },      // Create a "private" subpath in your dataset      "private": {        ".read": "auth.uid === $uid"      }    }  }}

Mixed public and private access

{  // Allow anyone to read data, but only authenticated content owners can  // make changes to their data  "rules": {    "some_path/$uid": {      ".read": true,      // or ".read": "auth.uid !== null" for only authenticated users      ".write": "auth.uid === $uid"    }  }}

Cloud Storage

Group-based access

//AllowreadsifthegroupIDinyourtokenmatchesthefilemetadata`owner`property//AllowwritesifthegroupIDisintheuser's custom tokenmatch /files/{groupId}/{fileName} {  allow read: if resource.metadata.owner == request.auth.token.groupId;  allow write: if request.auth.token.groupId == groupId;}

Content owner only

// Grants a user access to a node matching their user IDservicefirebase.storage{match/b/{bucket}/o{// Files look like: "<use>r/UID/file.txt"match/user/{userId}/{fileName}{allowread,write:ifrequest.auth.uid==userId;}}}

Mixed public and private access

servicefirebase.storage{match/b/{bucket}/o{//Fileslooklike:"<use>r/UID/file.txt"match/user/{userId}/{fileName}{allowread;allowwrite:ifrequest.auth.uid==userId;}}}

(Realtime Database) Improperly inherited rules

Realtime Database Security Rules cascade, with rules at more shallow, parent paths overridingrules at deeper, child nodes. When you write a rule at a child node, rememberthat it can only grant additional privileges. You can't refine or revokeaccess to data at a deeper path in your database.

Not recommended: Refining rules at child paths
{  "rules": {     "foo": {        // allows read to /foo/*        ".read": "data.child('baz').val() === true",        "bar": {          /* ignored, since read was allowed already */          ".read": false        }     }  }}
Solution: Write rules at parent pathsthat are broad, and grant more specific privileges at child pathsIf your data access needs require more granularity, keep your rules granular.Learn more about cascadingRealtime Database Security Rules inCoresyntax ofRealtime Database Security Rules.

Closed access

While you're developing your app, another common approach is to keep yourdata locked down. Typically, this means you've closed off read and writeaccess to all users, as follows:

Cloud Firestore

// Deny read/write access to all users under any conditionsservicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:iffalse;}}}

Realtime Database

{  "rules": {    ".read": false,    ".write": false  }}

Cloud Storage

// Access to files throughCloud Storage is completely disallowed.// Files may still be accessible throughApp Engine orGoogle Cloud Storage APIs.servicefirebase.storage{match/b/{bucket}/o{match/{allPaths=**}{allowread,write:iffalse;}}}

The Firebase Admin SDKs and Cloud Functions can still access yourdatabase. Use these rules when you intend to useCloud Firestore orRealtime Database as a server-onlybackend in conjunction with the FirebaseAdmin SDK. While it is secure, you should test that your app's clients canproperly retrieve data.

Learn more aboutCloud Firestore Security Rules and how they work inGet Started withCloud Firestore Security Rules.

Test yourCloud Firestore Security Rules

To check your app's behavior and verify yourCloud Firestore Security Rules configurations,use theFirebase Emulator. Use theCloud Firestoreemulator to run and automate unit tests in a local environment before you deployany changes.

To quickly validateFirebase Security Rules in theFirebase console, usetheFirebase Rules Simulator.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-18 UTC.