【问题标题】:iOS Firebase/Firestore Permission DeniediOS Firebase/Firestore 权限被拒绝
【发布时间】:2019-02-24 14:00:48
【问题描述】:

我知道这个问题经常被问到,但是提出的解决方案并没有为我解决。

我尝试设置一个基本的 iOS Firestore 应用程序,该应用程序将一些文档写入集合中。 我遵循标准程序,将 GoogleService-Info.plist 添加到我的项目中,并在启动时调用 `FirebaseApp.configure()。

我的 Firestore 规则如下所示:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

现在,一旦我尝试将某些内容保存在集合中,Firebase 就会返回一个 Permission denied 错误。

如果我的规则是这样的:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

写入被接受。显然,该请求似乎不包含任何身份验证信息,但我找不到任何关于此的其他文档。我错过了什么?

感谢您的帮助!

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore firebase-security


    【解决方案1】:

    如果您在应用中使用身份验证,那么您应该使用

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth.uid != null;
        }
      }
    }
    

    这仅在您在应用中添加了 firebase 身份验证时才有效,但如果您没有添加,则它将返回 PermissionDenied

    你也可以用这个方法

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    

    但是这种方法并不安全,任何人都可以一次更改您的整个数据库,而且 Firebase 也不建议您使用这种方法。

    如果您处于开发模式,请使用它并创建您的数据库,但如果您要进行生产,您只需将其更改为任一

    allow read, write: if request.auth.uid != null;
    

    或者如果您的应用中没有身份验证。

    allow read, write: if false;
    

    希望这能帮助你更好地理解。

    【讨论】:

    • 谢谢。但是我问自己 API 密钥有什么用处。当您只希望应用程序通常将信息上传到 Firestore 时,为什么必须对您的应用程序内的用户进行特殊身份验证?所以我的解决方案是为拥有这些权限的应用创建一个帐户。
    • 我已经在回答中提到了这一点,如果您在应用中使用身份验证,则必须使用第一个权限,但如果您不使用身份验证,则可以使用 if true; 仅用于开发目的,当您完成并将应用上传到 App Store 后,您需要使用 if false; 进行更改。如果您认为它有效,请接受我的回答。 :)
    【解决方案2】:

    我的猜测是,由于您没有使用 firebase 身份验证服务进行身份验证,因此请求缺少身份验证信息。

    来自 firebase 文档:

    身份验证 最常见的安全规则模式之一是根据用户的身份验证状态控制访问。例如,您的应用可能希望只允许登录用户写入数据

    service cloud.firestore {
      match /databases/{database}/documents {
        // Allow the user to access documents in the "cities" collection
        // only if they are authenticated.
        match /cities/{city} {
          allow read, write: if request.auth.uid != null;
        }
      }
    }
    

    https://firebase.google.com/docs/firestore/security/rules-conditions

    您可以在通过firebase身份验证服务进行身份验证后尝试该规则,并检查是否通过了规则。

    【讨论】:

    • 是的,当然会。你说得有道理。我只是希望有一种特殊的方式来处理 Firebase 应用程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2020-02-15
    • 2017-12-26
    相关资源
    最近更新 更多