How Can I Secure the Firebase Realtime database without Authenticating (Login/Register) the user?

Issue

I’m developing a Firebase Realtime database application. in the App, users don’t want to Authenticate.So, I make the rules as public

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

(User no need to register/login).but in the Firebase Realtime database section, it says as a Warning

Your security rules are defined as public, so anyone can steal, modify, or delete data in your database.

So, How can Secure the data without Authenticate(Login/Register) the user?

Solution

If you want to secure data access without requiring the user to sign in with their credentials, consider using Firebase’s anonymous authentication. With this provider, you can sign in a user with just this single line of code:

FirebaseAuth.getInstance().signInAnonymously();

After running this you won’t know any details of the users yet. But you can now identify the user in any calls to the database, and then use the information in the security rules of your database, to ensure the user only has access to the data they’re authorized for.

For an example of this, see the documentation on leveraging user information in security rules, which contains this example:

For example, your app may want to make sure users can only read and write their own data. In this scenario, you would want a match between the auth.uid variable and the user ID on the requested data:

{
  "rules": {
    "users": {
      "$userId": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($userId)
        ".write": "$userId  auth.uid"
      }
    }
  }
}

To learn more about that, I recommend reading the full documentation on securing data access.

Answered By – Frank van Puffelen

Leave a Comment