How to prevent customers from modifying firebase d

2019-07-19 17:56发布

I've recently starting exploring firebase as a authentication solution for my angular JS single-page website, and it seems perfect. However from a security perspective I'm not very sure about keeping the logic on client-side in my application.

Suppose I have a check 'isProfileCompleted' for a customer who signs-up on my website, and is supposed to complete his profile. I'm keeping the data in a JSON keyed by the UID with exclusive write access to the customer only.

The problem is, now that the client has write access to his data, he can easily bypass client side validation checks by simply modifying javascript in his browser. Also, the client can easily update his account_type to author/moderator, as it's his data. Does firebase provide a solution to this problem?

Let me know if it's not clear, so I will try to elaborate further.

Thanks.

1条回答
干净又极端
2楼-- · 2019-07-19 18:13

You can secure your data with Security Rules.

Firebase Security Rules are an expression (does the true evaluate to true/false) based rules language that live on a Firebase server and validate whether the current user can access your data.

Take the following data structure:

{
  // the users of the app
  "users": {
    "1": {
      "name": "Sanjay",
      "isProfileCompleted": true
    },
    "2": {
      "name": "David",
      "isProfileCompleted": false
    }
  }
}

By default anyone can read or write data to your Firebase database. To fix this you can write security rules.

Security Rules are essentially an annotation on your data structure:

{
  "rules": {
     "users": { // /users is read only
       ".read": true,
       ".write": false
     }
   }
}

Security Rules give you access to a set of server variables to check your rules against. The most commonly used one is the auth variable which lets you check against the currently authenticated user. You can also create wildcard variables with the $, which acts a route parameter creating.

{
  "rules": {
    "users": {
      // users can read and write their own data, but no one else. 
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }
    }
  }
}

You can even write rules to validate the structure of your data.

{
  "rules": {
    "users": {
      // users can read and write their own data, but no one else. 
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid",
        ".validate": "newData.hasChildren(['name', 'isProfileCompleted']),
          "name": {
            ".validate": "newData.isString()"
          },
          "isProfileCompleted": {
             ".validate": "newData.isBoolean()"
           }
      }
    }
  }
}

But the Bolt compiler is a better solution for this, as it allows you to create Types to define schema.

You can write your Security Rules in the Firebase App Dashboard or you can upload them via the Firebase CLI.

查看更多
登录 后发表回答