瞭解適用於 Cloud Storage 語言的 Firebase 安全性規則核心語法

您可以透過 Cloud Storage 的 Firebase 安全性規則,控管已儲存物件的存取權 建立一組容器彈性規則語法可讓您建立 任何作業 (從所有寫入至 Cloud Storage 的作業) 的控管規則 對特定檔案執行各種作業

本指南將說明 Cloud Storage 安全性規則的基本語法和結構, 以及建立完整的規則集

宣告服務和資料庫

Cloud Storage 的 Firebase 安全性規則開頭一律為下列宣告:

service firebase.storage {
    // ...
}

service firebase.storage 宣告會將規則的範圍限定為 Cloud Storage,防止 Cloud Storage 安全性規則與 Cloud Firestore 等其他產品的規則

基本讀取/寫入規則

基本規則包含識別 Cloud Storage 的 match 陳述式。 值區、指定檔案名稱的比對陳述式以及 allow 運算式 讀取指定資料時允許的詳細資料allow 運算式 指定涉及的存取方法 (例如讀取、寫入) 和條件 允許或拒絕存取。

在預設規則集中,第一個 match 陳述式使用 {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

比對萬用字元

除了指向單一檔案,規則也可以使用萬用字元 指向名稱中含有指定字串前置字元 (包括斜線) 的任何檔案 與 match /images/{imageId} 相同。

在上述範例中,比對陳述式使用 {imageId} 萬用字元語法。 這表示這項規則適用於檔案名稱開頭為 /images/ 的任何檔案, 例如 /images/profilePhoto.png/images/croppedProfilePhoto.png當 系統會評估比對陳述式中的 allow 運算式,也就是 imageId 變數 會解析為圖片檔案名稱,例如 profilePhoto.pngcroppedProfilePhoto.png

您可以在 match 中參照萬用字元變數,以便提供檔案 名稱或路徑授權:

// Another way to restrict the name of a file
match /images/{imageId} {
  allow read: if imageId == "profilePhoto.png";
}

階層式資料

如先前所說, Cloud Storage 值區但只要使用檔案命名慣例,通常不會發生這種情況 即使檔案名稱包含斜線,我們可以假示 巢狀目錄和子目錄請務必瞭解 Firebase 安全性規則與這些檔案名稱的互動情形。

假設一組檔案名稱開頭都是 /images/ stem。Firebase 安全性規則只會套用到相符的檔案名稱,因此存取 /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

在上述規則中,檔案「images/profilePhoto.png」就能讀取 conditionother_condition 的值為 true,而檔案 「images/users/user:12345/profilePhoto.png」只有在結果為 other_condition

Cloud Storage 安全性規則不會串聯,並且只有當 要求路徑與包含指定規則的路徑相符。

版本 1

根據預設,Firebase 安全性規則會使用第 1 版。在第 1 版中,遞迴萬用字元 符合一或多個檔案名稱元素,而不是零或多個元素。因此, match /images/{filenamePrefixWildcard}/{imageFilename=**} 與檔案名稱相符 例如 /images/profilePics/profile.png,而不是 /images/badge.png。使用 請改為使用「/images/{imagePrefixorFilename=**}」。

遞迴萬用字元必須放在比對陳述式的結尾。

建議您改用第 2 版,以便享有更強大的功能。

版本 2

在第 2 版的 Firebase 安全性規則中,遞迴萬用字元符合零或多個路徑 項目。因此,「/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>;
   }
  }
}

精細運算

在某些情況下,將 readwrite 細分為更常見的 ID 執行精細作業舉例來說,您的應用程式可能想強制執行 而非刪除檔案時的條件。

read 作業可拆分為 getlist

write 規則可 細分為 createupdatedelete

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 (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;
    }
  }
}

在上述範例中,所有讀取及寫入名稱開頭為 系統允許「/images/」,因為第二項規則一律為 true,即使 第一項規則是 false

規則不是篩選器

保護資料並開始執行檔案作業後,請謹記 但安全性規則並不是篩選器您無法對一組 符合檔案名稱模式的檔案,並預期 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

Web
filesRef = storage.ref().child("aFilenamePrefix");

filesRef.listAll()
    .then(function(result) {
      console.log("Success: ", result.items);
    })
});

Cloud Storage 安全性規則中的規則會依據每項查詢的潛在機率評估 結果,如果可以傳回用戶端確實的檔案,則要求失敗。 沒有讀取權限。存取要求必須遵循 規則。

後續步驟

深入瞭解 Cloud Storage 的 Firebase 安全性規則:

您可以探索 Cloud Storage 專屬的 Firebase 安全性規則用途: