Home > other >  Firebase real time database read and write without authentication?
Firebase real time database read and write without authentication?

Time:12-13

I'm building a simple game with a high score list containing user's name and score. I really wouldn't like to use any login or authentication, as the game is very simple and I just want people to be able to play it fast without a hassle. What's my best option to "secure" the real time database, as I need to allow user to read and write to database in order the game to work? I'm using the free tier of Firebase and my main concern is that someone could exceed my limits on purpose.

CodePudding user response:

You're going to need some access rules once you deploy the app. Otherwise, someone can delete your entire database with a single request. It's not difficult to implement a basic authentication system in Firebase - that's one of the main selling points of using Firebase in the first place. The easiest to setup is anonymous, then social auth, followed by email link auth.

https://firebase.google.com/docs/rules/insecure-rules

CodePudding user response:

Securing the database doesn't necessarily mean that you need to ask your users for sign-in credentials. For example, if you use Firebase Authentication's anonymous sign-in, each user gets a unique, non-spoofable UID that you can use to secure access in security rules without them ever entering credentials.

CodePudding user response:

I would recommend the Anonymous authentication feature of Firebase, which assigns a unique 28-character string as the UID of each visitor. I believe the UID persists between site visits by default.

Then you can use database rules to secure your database. Here's an example database.rules.json that would:

  • Allow anyone to read from a particular location /games/$gameName/$uid (and child nodes)
  • Only allows the authenticated player to write to /games/$gameName/$uid/$gameNumber/ (and child nodes) and not allow data to be overwritten
  • Allow the authenticated player to write only a string value of length 1 to /games/$gameName/$uid/$gameNumber/gameComplete

The last point could be helpful for controlling the size of writes to not exceed your limit. But also keep in mind that the free Spark plan will simply stop functioning if you go beyond your limit. You will not suddenly incur costs unless you have upgraded to Blaze plan which requires a credit card.

N.B. The $ notation for wildcard key names in the database.

{
  "rules": {
    "games": {
      "$gameName": {
        "$uid": {
          ".read": true,
          "$gameNumber": {
            ".write": "$uid === auth.uid && !data.exists()",
            "gameComplete": {
              ".write": "newData.isString() && newData.val().length === 1"
            }
          },
        }
      }
    }
  }
}
  • Related