如何使Firebase Admin SDK帐户尊重验证规则?

时间:2016-11-30 03:56:11

标签: javascript firebase firebase-realtime-database firebase-authentication

我有node server运行firebase Admin SDK并进行身份验证:

 admin.initializeApp({
        databaseURL: 'https://brandonsCoolApp.firebaseio.com',
        credential: admin.credential.cert(firebaseCredentials),
 })


 // firebase security rules (abridged version; i have several validation rules)
    {
      "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }

这适用于正常操作。但是,它在Firebase安全/验证规则中获得特殊状态,并且会忽略所有规则。

我希望尊重验证规则。因此,根据Firebase Docs,我尝试添加自定义auth.uid并调整我的安全规则:

 admin.initializeApp({
        databaseURL: 'https://brandonsCoolApp.firebaseio.com',
        credential: admin.credential.cert(firebaseCredentials),
        databaseAuthVariableOverride: {
          uid: "node-server"
        }
    })

// firebase security rules
{
  "rules": {
    ".read": "auth != null || auth.uid == 'node-server'",
    ".write": "auth != null || auth.uid == 'node-server'"
  }
}

// I also tried this version
{
      "rules": {
        ".read": "auth.uid === 'node-server'",
        ".write": "auth.uid === 'node-server'"
      }
    }

但是,当尝试在任意路径上调用PERMISSION_DENIED时,这会导致update()错误:

FIREBASE WARNING: update at / failed: permission_denied
{ [Error: PERMISSION_DENIED: Permission denied] code: 'PERMISSION_DENIED' }

所以:我怎样才能说服我的坏男孩admin SDK server按照规则理顺和玩耍?

1 个答案:

答案 0 :(得分:2)

所以,我上面的验证规则是正确的。我将PERMISSION DENIED错误混淆为身份验证问题,实际上这与验证规则失败时获得的邮件相同。

最终这个init代码起作用了:

admin.initializeApp({
        databaseURL: 'https://brandonsCoolApp.firebaseio.com',
        credential: admin.credential.cert(firebaseCredentials),
        databaseAuthVariableOverride: {
          uid: "node-server"
        }
    })

// firebase security rules
{
  "rules": {
    ".read": "auth != null || auth.uid == 'node-server'",
    ".write": "auth != null || auth.uid == 'node-server'"
  }
}

我在调用update()之前将json有效负载写入update(),然后将json内容复制/粘贴到firebase规则中,弄明白我的验证错误是什么模拟器。在那里,您可以逐行分析更新失败的原因。