Saturday, October 8, 2022

Firebase database security rule samples

Firebase database security rule samples 

All Authenticated users

{

  "rules": {

    ".read": "auth.uid !== null",

    ".write": "auth.uid !== null"

  }

}


Content owner only access 

{

  "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"

      }

    }

  }

}



Attribute based Role based access 


{

  "rules": {

    "some_path": {

      "${subpath}": {

        //

        ".write": "root.child('users').child(auth.uid).child('role').val() === 'admin'",

        ".read": true

      }

    }

  }

}


Custom Claim based rules 

{

  "rules": {

    "some_path": {

      "$uid": {

        // Create a custom claim for each role or group

        // you want to leverage

        ".write": "auth.uid !== null && auth.token.writer === true",

        ".read": "auth.uid !== null && auth.token.reader === true"

      }

    }

  }

}


Tenant based rules 


{

  "rules": {

    "some_path": {

      "$uid": {

        // Only allow reads and writes if user belongs to a specific tenant

        ".write": "auth.uid !== null && auth.token.firebase.tenant === 'tenant2-m6tyz'",

        ".read": "auth.uid !== null

      }

    }

  }




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"

      }

    }

  }

}

References :

https://firebase.google.com/docs/rules/basics 

No comments:

Post a Comment