简体   繁体   English

Firebase规则-限制对管理员的访问

[英]Firebase rules - restricting access to admin

I have an adminContent node in my Firebase database which should only be read/write accessible if a user has admin set to true as custom claim. 我的Firebase数据库中有一个adminContent节点,只有在用户将admin设置为true作为自定义声明时,才可以对其进行读写访问。

The following code shows that one of my test users HAS admin set to true as claim and one test user HAS NOT (so the problem doesn't seem to be setting the claim correctly): 以下代码显示我的一个测试用户将admin设置为true作为声明,而一个测试用户将NOT设置为true(因此,问题似乎未正确设置声明):

/* Check if admin */
firebase.auth().currentUser.getIdTokenResult().then(function(idTokenResult) {
   if (idTokenResult.claims.admin) {
    // THIS PART IS EXECUTED

   }
});

These are my rules: 这些是我的规则:

{
  "rules": {
    "metadata": {
      "$user_id": {
        // Read access only granted to the authenticated user.
        ".read": "$user_id === auth.uid",
        // Write access only via Admin SDK.
        ".write": false
      }
    },
    "adminContent": {
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true",
    }
  }
}

Both test users (one with admin claim and one without) are able to read and write to adminContent. 两个测试用户(一个有admin声明,一个没有admin声明)都可以读写adminContent。 And when I test the simulator under rules on the Firebase console with the UIDs of the two users none get permission. 当我在Firebase控制台上的规则下使用两个用户的UID测试模拟器时,没有人获得许可。

Data structure is as follows: 数据结构如下:

adminContent
    adminEmails
    announcements
metadata
    ...
users
    ...

Is there anything wrong with my rules? 我的规则有什么问题吗? Why do the simulator and real scenario differ? 为什么模拟器和实际场景不同?

It is possible that the token is outdated, ie. 令牌可能已过时,即。 the custom claim was set after the ID token was issued. 自定义声明是在颁发ID令牌后设置的。 The token lifetime is 1 hour. 令牌寿命为1小时。 So until the next refresh, the token will not pick up the latest claims. 因此,在下一次刷新之前,令牌将不会提取最新的声明。 You can force it to refresh after the custom claim is set by calling: 在设置自定义声明后,您可以通过以下方式强制其刷新:

firebase.auth().currentUser.getIdTokenResult(true)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM