且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase:针对同一个项目中的每个应用程序进行自定义验证

更新时间:2023-11-22 16:48:16

您无法保护数据库访问权限,以允许特定的应用程序或特定设备。请参阅如何防止其他人访问我的Firebase

但是,如果您使用Firebase身份验证,则设备可以轻松映射到属于特定用户。如果您不想要求用户登录,则甚至可以使用匿名身份验证。对于Firebase身份验证,每个用户都有唯一的用户ID(Firebase条款中的UID)。当你知道用户的UID时,你可以根据该UID保证对数据库的访问。



最近一个项目的例子:


$ b $
  {
rules:{
.read:true,
.write:auth != null&&
root.child('config / whitelist')。child(auth.uid).exists()
}
}
$因此,在这里,如果登录用户的UID出现在节点 / config / whitelist下,我们允许编写它。例如:
$ b $ pre $ code $ config
白名单
jn0BrHQqUEYSjqvqfqzbJTMOlZ82:true
ytEtWqOfLkRk3OUjTKBtZnTehZc2true


My problem is my project has 2 application. One application just run in a specific mobile device which we known, it interact with firebase without authenication. The another is run in many mobile devices, it must sign-in into firebase to communicate each other.

So, what I want to do is how to configure database rule in firebase to 2 app can use the same the database? Thank everyone very much! Appologize for my bad english.

You cannot secure database access to allow a specific app or a specific device. See How to prevent other access to my firebase.

But a device can easily be mapped to belong to a specific user, if you use Firebase Authentication. You could even use anonymous authentication if you don't want to require that the user signs in. With Firebase Authentication each user has a unique user id (UID in Firebase terms). And when you know the UID for the user, you can secure access to the database based on that UID.

An example from a recent project:

{
  "rules": {
    ".read": true,
    ".write": "auth != null && 
               root.child('config/whitelist').child(auth.uid).exists()"
  }
}

So here, we allow writing if the signed-in user's UID is present under a node /config/whitelist. E.g.

config
   whitelist
     "jn0BrHQqUEYSjqvqfqzbJTMOlZ82": true
     "ytEtWqOfLkRk3OUjTKBtZnTehZc2" true