本文介绍了一些 Firebase 安全规则适用于 Cloud Functions 中的管理员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cloud Function 在更新或删除时收到 Firebase 权限被拒绝错误.

Cloud Function gets a firebase permission denied error when updating or removing.

使用文件中的凭据初始化服务帐户,以便使用当前不可用于默认帐户的 auth.createCustomToken

The service account is initialized with credentials from a file in order to use auth.createCustomToken which isn't currently available for the default account

admin = require('firebase-admin');
functions = require('firebase-functions');
credential = admin.credential.cert(require('./credentials.json'));
admin.initializeApp({credential: credential, databaseURL: functions.config().firebase.databaseURL});

阻止更新的安全规则:

"downloads": {
  "$key": {
    ".write": "data.val() == null"
  }
}

用户使用 push 将数据插入 /downloads,然后 Cloud Function 尝试更新并随后删除.即使管理员帐户应该绕过包括验证在内的所有安全规则,这两个操作都会失败.

The user inserts data with push into /downloads then Cloud Function tries to update and subsequently remove. Both of these operations fail even though admin accounts supposedly bypass all security rules including validation.

FIREBASE WARNING: update at /downloads/-Kexz33ljYjKblF_ZgUo failed: permission_denied
FIREBASE WARNING: set at /downloads/-Kexz33ljYjKblF_ZgUo failed: permission_denied

如果我将规则更改为这样,第一个错误(更新)就会消失:

The first error (update) disappears if I change the rules to this:

"downloads": {
  "$key": {
    ".write": "newData.child('uid').val() == auth.uid"
  }
}

更新

解决方法是将 event.data.ref 重新定义为

ref = admin.database().ref(event.data.ref.path.toString())

推荐答案

event.data 对象返回到您的 Cloud Function 的 onWrite() 回调,有两种类型的数据库引用:一种范围为相同作为触发写入的用户的权限 (event.data.ref)和一个具有管理员权限的范围,授予完全读写访问权限(event.data.adminRef).我无法确定,因为您没有提供显示 Cloud Function 的代码示例,但我敢打赌您使用的是 event.data.ref.改用 event.data.adminRef 应该可以解决您的问题.

Within the event.data object returned to your Cloud Function's onWrite() callback, there are two types of Database references: one that is scoped to to the same permissions as the user who triggered the write (event.data.ref) and one that is scoped with admin rights, granting full read and write access (event.data.adminRef). I can't tell since you didn't provide a code sample showing your Cloud Function, but I bet you are using event.data.ref. Switching to use event.data.adminRef should resolve your problem.

这篇关于一些 Firebase 安全规则适用于 Cloud Functions 中的管理员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:59