Firebase实时数据库安全规则,以允许特定用户 [英] firebase realtime db security rule to allow specific users

查看:86
本文介绍了Firebase实时数据库安全规则,以允许特定用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的Firebase实时安全规则如下

my current firebase realtime security rules are like below

{
  "rules": {
    "users": {
      ".read" : true,
      ".indexOn": ["email"],
      "$user_id": {
        ".read": true,
        ".write": "auth != null && $user_id === auth.uid"
      }
    }
  }
}

他们转换为只有经过身份验证的用户才能将数据写入用户/之下的自己的节点

they translates as only the authenticated user can write the data to his own node under users/

但是,我们有管理员用户,他们应该能够修改非管理员用户的数据.

However, we have admin users who should be able to modify the data of non admin users.

我们识别管理员用户的方式是用户属性isAdmin,这对于管理员用户是正确的.因此,具有管理员和非管理员用户的示例数据如下所示:

The way we identify admin users are a user property isAdmin which is true for admin users. so the sample data with a admin and non admin user looks like below

{
"users": {
 "kldjjfjf" : {
                 "name": "vik", "isAdmin": true
              },
 "lfllfomr": {
                 "name": "neeti", "isAdmin": false
             }
}

请告知处理此类用例的最佳实践是什么?进行.write true将解决此问题,但随后它将使所有人可以修改任何人的数据.

Please advise what is the best practice to handle this kind of usecases? doing a .write true will solve it but then it will make it open to anyone to modify anyone's data.

推荐答案

我发现允许管理访问的最简单方法是:

The simplest ways I've found to allow Administrative access is to:

  1. 对管理员使用自定义声明
  2. 使用管理员UID白名单

对管理员使用自定义声明

您可以使用Admin SDK将自定义声明添加到Firebase身份验证用户配置文件.声明是您确定自己含义的自定义键/值对.文档中的第一个示例显示将称为admin的声明设置为true ,例如使用Node.js的Admin SDK:

Use a custom claim for admins

You can add custom claims to Firebase Authentication user profiles with the Admin SDK. Claims are custom key/value pairs that you determine the meaning of yourself. The first example from the documentation shows setting a claim called admin to true, for example with the Admin SDK for Node.js:

admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});

设置了自定义声明后,它将在登录时传输到客户端,并且在安全规则中也可用.您可以使用以下方法检查以上内容:

Once a custom claim is set, it is transported to the client when it signs in, and is also available in security rules. You can check the above with:

".write": "auth != null && ($user_id === auth.uid || auth.token.admin === true)"

使用管理员UID白名单

一种简单的替代方法是将具有特定特权的UID列表存储在用户数据库中.例如,您可能有一个顶级Admins列表:

Admins
  uidOfVik: true
  uidOfPuf: true

以上表示您和我是管理员.然后,检查安全规则中的内容:

The above means that you and me are admins. You then check for those in the security rules:

".write": "auth != null && ($user_id === auth.uid || root.child('Admins').child(auth.uid).exists())"

这篇关于Firebase实时数据库安全规则,以允许特定用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆