【问题标题】:Firestore security rules when updating database from a script that doesn't have auth从没有身份验证的脚本更新数据库时的 Firestore 安全规则
【发布时间】:2018-08-25 17:43:26
【问题描述】:

我正在使用这些 Firestore 安全规则:

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

问题是,对于我的 react-native 应用程序中的功能,执行回调(以共享事务 id)并且应用程序退出到浏览器以处理回调。在我服务器上的回调脚本中,我有一些这样的代码:

        fetch(url, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
            }
        }).then(response => {

          if (response.ok) {
            response.json().then(json => {

                if(json.data == "Manual sale") {
                    alert("Manual sale complete! Return to Fairstarter!");
                    return;
                }

                var quant = 0;
                var itemsRef = db.collection('items');
                var query = itemsRef.where('barcode', '==', String(json.data)).get()
                    .then(snapshot => {

                      snapshot.forEach(doc => {

                          ....

                          //UPDATE THAT IS LOCKED OUT BY PERMISSIONS
                          itemsRef.doc(doc.id).update({
                             [Object.keys(doc.data())[0]]]: {
                                quantity: newVal
                             }
                          })

问题是,在上面的块中,我尝试更新数据库,但是由于我不是来自具有现有 firebase 用户进行身份验证的东西,因此我被 firebase 拒绝,因为权限。

如何在允许回调脚本更新数据库的同时保证数据库安全?

【问题讨论】:

  • 请不要只贴一些一般的标签。确保您阅读标签信息并为您的问题获取正确的标签。例如,firebase-database 标签用于实时数据库而不是 Firestore。
  • javascript 是有道理的,但一个潜在的解决方案可能需要某种 javascript 匿名身份验证......显然只是一个猜测,因为我还没有找到答案

标签: javascript firebase google-cloud-firestore firebase-security


【解决方案1】:

使用 firebase 匿名登录工作,我在配置 firebase 后将其放在脚本的顶部:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        var isAnonymous = user.isAnonymous;
        //alert(user.uid);
        // ...
      } else {
        // User is signed out.
        // ...
      }
      // ...
    });

    firebase.auth().signInAnonymously().catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // ...
          alert(errorMessage);
    });

不要忘记在您的 Firebase 项目设置中启用匿名身份验证。

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 2021-07-05
    • 1970-01-01
    • 2021-04-08
    • 2018-04-04
    • 1970-01-01
    • 2020-06-23
    • 2021-07-12
    相关资源
    最近更新 更多