首页 > 解决方案 > Firebase 存储元数据未包含在安全规则中

问题描述

我正在尝试实施 Firebase 存储规则,以便只有帖子作者可以创建、删除和更新它。问题是在模拟器中它工作得很好,但在实际情况下却没有。对我来说,我使用的元数据似乎没有出现在规则中,或者没有包含在 put 请求中。

我按照文档中的说明做所有事情:

这些是我的规则:

service firebase.storage {
  match /b/{bucket}/o {
  //Posts
    match /{allImages=**} {
       allow read: if authenticated();
       allow create: if authenticated() && metadata().userId == request.auth.uid;
       allow update, delete: if authenticated() && metadata().userId == request.auth.uid;
    }
    }
  function metadata() { return request.resource.metadata; }
  function authenticated() { return request.auth.uid != null; }
}

这是我用来上传文件的功能:

uploadFile({ commit, rootState }, payload) {
    const storageRef = firebase
      .storage()
      .ref(`posts/${payload.id}/${payload.index}/${payload.index}`)
    commit('app/setError', null, { root: true })
    commit('app/setLoading', true, { root: true })
    return new Promise((resolve, reject) => {
      storageRef
        .put(payload.file, {
          userId: rootState.authentication.user.id
        }) //HERE IS THE METADATA AS THE SECOND PARAMETER (userId)
        .then(snapshot => {
          snapshot.ref.getDownloadURL().then(downloadURL => {
            resolve(downloadURL)
            commit('app/setLoading', false, { root: true })
          })
        })
        .catch(error => {
          reject(error)
          commit('app/setError', error, { root: true })
          commit('app/setLoading', false, { root: true })
        })
    })
  },

编辑 1:这是我在模拟器中测试的对象元数据:

{"metadata":{"userId":"9PuxRiKI17Y8hbwW9aVISpdrpZa2"},"name":"b/myprojectid-develop.appspot.com/o/posts/{postId}","bucket":"myprojectid-develop.appspot.com"}

这是我在真实案例中作为元数据发布的缩小对象:

{"userId":"9PuxRiKI17Y8hbwW9aVISpdrpZa2"}

我做错了什么?任何帮助表示赞赏!

标签: javascriptfirebasefirebase-storagefirebase-security

解决方案


我确实联系了 Firebase 支持,他们提供的解决方案是将元数据对象包装在里面customMetadata,如下所示:

storageRef
.put(payload.file, {
   customMetadata: { //This is the required key
      userId: <your user id data>
   }
})

注意!这似乎记录在这里


推荐阅读