Cloud Storage 的 Firebase Security Rules 可讓您控管 Cloud Storage bucket 中儲存的物件存取權。彈性的規則語法可讓您建立規則,控管任何作業,從 Cloud Storage bucket 的所有寫入作業到特定檔案的作業,都能控管。
AI 輔助功能的 AI 提示
如需 AI 輔助,請將下方提示詞複製到 AI 程式設計代理 (例如 Android Studio 內建 Gemini、Antigravity、Claude Code、Codex 和 Cursor)。您可以自訂提示,並與代理反覆調整。如需詳細安裝資訊,請參閱 Firebase 代理技能。
Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me write, validate, and deploy Firebase Security Rules to protect my app's Cloud Storage data.
本指南說明 Cloud Storage Security Rules 的基本語法和結構,協助您建立完整的規則集。
服務和資料庫宣告
Cloud Storage 的 Firebase Security Rules 一律以下列宣告開頭:
service firebase.storage {
// ...
}
service firebase.storage 宣告會將規則範圍限定在 Cloud Storage,避免 Cloud Storage Security Rules 與其他產品 (例如 Cloud Firestore) 的規則發生衝突。
基本讀取/寫入規則
基本規則包含 match 陳述式 (用於識別 Cloud Storage bucket)、比對陳述式 (用於指定檔案名稱),以及 allow 運算式 (用於詳細說明何時允許讀取指定資料)。allow 運算式會指定涉及的存取方法 (例如讀取、寫入),以及允許或拒絕存取的條件。
在預設規則集中,第一個 match 陳述式會使用 {bucket} 萬用字元運算式,表示規則適用於專案中的所有 bucket。我們會在下一節進一步討論萬用字元比對的概念。
service firebase.storage {
// The {bucket} wildcard indicates we match files in all Cloud Storage buckets
match /b/{bucket}/o {
// Match filename
match /filename {
allow read: if <condition>;
allow write: if <condition>;
}
}
}
所有比對陳述式都指向檔案。比對陳述式可以指向特定檔案,例如 match /images/profilePhoto.png。
比對萬用字元
除了指向單一檔案外,Security Rules 還可以使用萬用字元指向名稱中含有指定字串前置字元的任何檔案 (包括斜線),例如 match /images/{imageId}。
在上述範例中,比對陳述式使用 {imageId} 萬用字元語法。這表示規則適用於名稱開頭為 /images/ 的任何檔案,例如 /images/profilePhoto.png 或 /images/croppedProfilePhoto.png。評估比對陳述式中的 allow 運算式時,imageId 變數會解析為圖片檔案名稱,例如 profilePhoto.png 或 croppedProfilePhoto.png。
您可以在 match 中參照萬用字元變數,提供檔案名稱或路徑授權:
// Another way to restrict the name of a file
match /images/{imageId} {
allow read: if imageId == "profilePhoto.png";
}
階層式資料
如前所述,Cloud Storage bucket 內沒有階層結構。不過,只要使用檔案命名慣例 (通常是在檔案名稱中加入斜線),就能模擬出類似巢狀目錄和子目錄的結構。請務必瞭解 Firebase Security Rules 如何與這些檔案名稱互動。
假設有一組檔案,名稱開頭都是 /images/ 詞幹。Firebase Security Rules 只會套用至相符的檔案名稱,因此在 /images/ 詞幹上定義的存取控管不會套用至 /mp3s/ 詞幹。請改為編寫明確規則,比對不同的檔案名稱模式:
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
allow read, write: if <condition>;
}
// Explicitly define rules for the 'mp3s' pattern
match /mp3s/{mp3Id} {
allow read, write: if <condition>;
}
}
}
巢狀結構 match 陳述式中,內部 match 陳述式的路徑一律會附加至外部 match 陳述式的路徑。因此,下列兩個規則集等效:
service firebase.storage {
match /b/{bucket}/o {
match /images {
// Exact match for "images/profilePhoto.png"
match /profilePhoto.png {
allow write: if <condition>;
}
}
}
}
service firebase.storage {
match /b/{bucket}/o {
// Exact match for "images/profilePhoto.png"
match /images/profilePhoto.png {
allow write: if <condition>;
}
}
}
遞迴比對萬用字元
除了比對並傳回檔案名稱結尾字串的萬用字元外,您也可以在萬用字元名稱中加入 =**,宣告多區隔萬用字元,進行更複雜的比對,例如 {path=**}:
// Partial match for files that start with "images"
match /images {
// Exact match for "images/**"
// e.g. images/users/user:12345/profilePhoto.png is matched
// images/profilePhoto.png is also matched!
match /{allImages=**} {
// This rule matches one or more path segments (**)
// allImages is a path that contains all segments matched
allow read: if <other_condition>;
}
}
如果有多項規則符合檔案,結果會是所有規則評估結果的 OR。也就是說,如果檔案符合的任何規則評估結果為 true,則結果為 true。
在上述規則中,如果 condition 或 other_condition 評估為 true,則可以讀取檔案「images/profilePhoto.png」,而檔案「images/users/user:12345/profilePhoto.png」僅受 other_condition 的結果影響。
Cloud Storage Security Rules 不會串聯,只有在要求路徑與指定規則的路徑相符時,系統才會評估規則。
版本 1
Firebase Security Rules 預設使用第 1 版。在第 1 版中,遞迴萬用字元會比對一或多個檔案名稱元素,而非零或多個元素。因此,match /images/{filenamePrefixWildcard}/{imageFilename=**} 會比對 /images/profilePics/profile.png 等檔案名稱,但不會比對 /images/badge.png。請改用 /images/{imagePrefixorFilename=**}。
遞迴萬用字元必須位於比對陳述式的結尾。
建議您使用第 2 版,享受更強大的功能。
第 2 版
在 Firebase Security Rules 第 2 版中,遞迴萬用字元會比對零或多個路徑項目。因此,/images/{filenamePrefixWildcard}/{imageFilename=**} 會比對檔案名稱 /images/profilePics/profile.png 和 /images/badge.png。
您必須在安全性規則頂端加入 rules_version = '2';,才能選擇加入第 2 版:
rules_version = '2';
service cloud.storage {
match /b/{bucket}/o {
...
}
}
每個比對陳述式最多只能有一個遞迴萬用字元,但在第 2 版中,您可以將這個萬用字元放在比對陳述式中的任何位置。例如:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
// Matches any file in a songs "subdirectory" under the
// top level of your Cloud Storage bucket.
match /{prefixSegment=**}/songs/{mp3filenames} {
allow read, write: if <condition>;
}
}
}
精細作業
在某些情況下,建議將 read 和 write 細分為更精細的操作。舉例來說,應用程式可能想對檔案建立和檔案刪除強制執行不同的條件。
read 作業可分為 get 和 list。
write 規則可分為 create、update 和 delete:
service firebase.storage { match /b/{bucket}/o { // A read rule can be divided into read and list rules match /images/{imageId} { // Applies to single file read requests allow get: if <condition>; // Applies to list and listAll requests (Security Rules Version 2) allow list: if <condition>; // A write rule can be divided into create, update, and delete rules match /images/{imageId} { // Applies to writes to file contents allow create: if <condition>; // Applies to updates to (pre-existing) file metadata allow update: if <condition>; // Applies to delete operations allow delete: if <condition>; } } } }
重疊的比對陳述式
檔案名稱可能與多個 match 陳述式相符。如果有多個 allow 運算式與要求相符,只要「任一」條件為 true,系統就會允許存取:
service firebase.storage {
match b/{bucket}/o {
// Matches file names directly inside of '/images/'.
match /images/{imageId} {
allow read, write: if false;
}
// Matches file names anywhere under `/images/`
match /images/{imageId=**} {
allow read, write: if true;
}
}
}
在上述範例中,即使第一個規則是 false,第二個規則一律為 true,因此系統允許對名稱開頭為 /images/ 的檔案進行所有讀取和寫入作業。
規則不是篩選器
保護資料並開始執行檔案作業後,請注意,安全性規則並非篩選器。您無法對一組符合檔案名稱模式的檔案執行作業,並預期 Cloud Storage 只會存取目前用戶端有權存取的檔案。
舉例來說,請看以下安全性規則:
service firebase.storage {
match /b/{bucket}/o {
// Allow the client to read files with contentType 'image/png'
match /aFileNamePrefix/{aFileName} {
allow read: if resource.contentType == 'image/png';
}
}
}
拒絕:這項規則會拒絕下列要求,因為結果集可能包含 contentType 不是 image/png 的檔案:
網頁
filesRef = storage.ref().child("aFilenamePrefix"); filesRef.listAll() .then(function(result) { console.log("Success: ", result.items); }) });
Cloud Storage Security Rules 中的規則會根據潛在結果評估每項查詢,如果查詢可能傳回用戶端無權讀取的檔案,則會失敗。存取要求必須遵循規則設定的限制。
後續步驟
你可以深入瞭解Cloud Storage的Firebase Security Rules:
瞭解規則語言的下一個重要概念:動態條件。這類條件可讓規則檢查使用者授權、比較現有和傳入的資料、驗證傳入的資料等。
查看常見的安全性用途,以及Firebase Security Rules定義如何解決這些問題。
您可以探索Cloud Storage專屬的 Firebase Security Rules 用途: