【问题标题】:Firebase Storage Security Rules - Property size is undefined on objectFirebase 存储安全规则 - 对象的属性大小未定义
【发布时间】:2020-10-07 22:53:02
【问题描述】:

我正在尝试使用以下代码 (request.resource.size < 5 * 1024 * 1024) 对文件上传大小施加限制,上传图片时出现权限被拒绝错误。

在模拟器中运行后,我得出的结论是导致错误的要求是小于 5MB 检查的大小。在模拟器中抛出错误(Property size is undefined on object.),当我检查 request.resource 对象时,没有size 属性,只有contentTypenamebucket

我怎样才能正确地施加这个 5MB 的限制?

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /profile_images/{profileImgId}/{imgId} {
      allow create, update: if request.auth.uid == profileImgId
                    && request.resource.size < 5 * 1024 * 1024
                    && request.resource.contentType.matches('(?i)image/(jpeg|jpg|png)');
      allow delete: if false;
      allow get: if request.auth.uid == profileImgId;
    }
  }
}

【问题讨论】:

  • @ThomsonTran 感谢您的链接,但这是有人在 cloud firestore 中使用云存储规则,而我正在尝试使用云存储中的云存储文档中的示例。
  • 您确定您确实在使用存储模拟器进行测试吗?我在我的规则中使用 request.resource.size 并且它正在工作,而且这与文档 firebase.google.com/docs/storage/security/… 匹配,所以我不知道它为什么会失败
  • @Oliver 是的,我确定它是存储模拟器 :-) 确实,我很困惑,因为它在文档中工作并且看起来合乎逻辑¯_(ツ)_/¯
  • 再一次,你确定它确实是存储模拟器吗?因为现在我一直在搜索,没有用于 Firebase 存储的模拟器...

标签: firebase google-cloud-storage firebase-storage firebase-security


【解决方案1】:

firebase 存储中的这个安全规则对我有用:-

5MB=5242880 字节

service firebase.storage {
  match /b/{bucket}/o {
    match /profile {
        allow read, write: if request.resource.size < 5 * 1024 * 1024;
    }
  }
}

成功(5242879 字节):

失败(5242881 字节):

【讨论】:

    【解决方案2】:

    只是一个建议 我还为我的 android 应用程序使用了与上面显示的 fatalcoder524 相同的代码。但我也想捕捉异常,无论是由于大小异常还是由于其他原因而导致的失败,所以我借助存储异常错误代码在客户端识别它们。 这是我的代码的 sn-p..

    int errCode = ((StorageException) exception).getErrorCode();
    if(errCode == ERROR_NOT_AUTHORIZED)
    Toast.makeText(view.getContext(),"Size of file must be\nless than 5 MB", Toast.LENGTH_LONG).show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 2023-03-22
      • 2020-07-03
      • 1970-01-01
      • 2020-03-24
      • 2022-01-18
      相关资源
      最近更新 更多