![](/img/trans.png)
[英]How to use Firestore Document Reference in Firebase Cloud Storage Security Rules?
[英]Can Firebase Cloud Storage rules validate against Firestore data?
我們可以使用 Firestore 數據來授予或限制對托管在 Firebase 雲存儲上的文件的訪問權限嗎?
我想用作 Firebase 安全規則的示例
allow write: if get(/databases/mydbname/documents/guilds/$(guildID)).data.users[(request.auth.uid)] in ["Admin", "Member"];
目前無法從其他產品的安全規則中訪問不同的Firebase產品。 請參閱: 有沒有辦法在firebase存儲規則中驗證用戶角色?
但似乎您正在嘗試檢查用戶的組成員身份。 我建議您將其建模為所謂的自定義聲明,而不是在數據庫中查找該組成員身份。 除了(或除此之外)將成員資格寫入數據庫之外,您還可以使用Firebase管理SDK將聲明“用戶{uid}是組{guild1}的成員”設置到用戶配置文件中 :
admin.auth().setCustomUserClaims(uid, {guild1: true}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});
完成后,您可以檢查安全規則中的公會成員資格:
allow read: if request.auth.token.guild1 == true;
(我不確定你是否/如何將公會會員資格建模為地圖,如果情況確實如此,我會更新這個答案。)
您可以在使用雲 function 觸發器上傳文件后追溯驗證和刪除文件。
警告:此技術並非防彈,因為如果 Cloud Function 觸發器失敗,無效文件將暫時或可能永久存儲在 Cloud Storage 中。 我的偏好是首先阻止上傳,但如果確定權限的邏輯位於 Firestore 中並且不能填充到自定義聲明中,那么如果您使用 Firebase 的客戶端 SDK 上傳文件,這是目前唯一的方法。 如果您正在構建任務關鍵型系統,則應將文件上傳到 Cloud Function,然后讓 Cloud Function 將文件存儲在 Cloud Storage 中。
上傳文件時,添加一些元數據來指示上傳者:
const storageRef = ref(
storage,
`files/${fileName}`,
);
const uploadTask = uploadBytesResumable(storageRef, file, {
customMetadata: {
uploaderId: userId,
},
});
設置存儲規則,確保用戶身份元數據可信:
match /files/{fileName} {
allow create: if request.auth != null &&
request.resource.metadata.uploaderId == request.auth.uid
}
創建一個可追溯驗證和刪除的雲 function 觸發器:
export const onFinalize = functions
.storage.object()
.onFinalize(async object => {
// We can trust object.metadata.uploaderId, so check Firestore if user is able to upload file
if (!(await canUploadFile(object.metadata.uploaderId, object.name))) {
await storage.bucket(object.bucket).file(object.name).delete();
throw new Error(
`Permission error: ${object.metadata.uploaderId} not allowed to upload ${object.name}`,
);
}
// Continue
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.