了解 Cloud Storage 語言的 Firebase 安全規則的核心語法

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 語句可以指向特定文件,如match /images/profilePhoto.png

匹配通配符

除了指向單個文件之外,規則還可以使用通配符來指向名稱中具有給定字符串前綴(包括斜杠)的任何文件,如match /images/{imageId}中所示。

在上面的示例中,匹配語句使用{imageId}通配符語法。這意味著該規則適用於名稱開頭為/images/的任何文件,例如/images/profilePhoto.png/images/croppedProfilePhoto.png 。當評估 match 語句中的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/詞幹開頭的文件的情況。 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

在上面的規則中,如果conditionother_condition計算結果為true,則可以讀取文件“images/profilePhoto.png”,而文件“images/users/user:12345/profilePhoto.png”僅受other_condition的結果影響。

雲存儲安全規則不會級聯,僅當請求路徑與指定規則的路徑匹配時才會評估規則。

版本1

Firebase 安全規則默認使用版本 1。在版本 1 中,遞歸通配符匹配一個或多個文件名元素,而不是零個或多個元素。因此, match /images/{filenamePrefixWildcard}/{imageFilename=**}匹配 /images/profilePics/profile.png 等文件名,但不匹配 /images/badge.png。請改用/images/{imagePrefixorFilename=**}

遞歸通配符必須出現在匹配語句的末尾。

我們建議您使用版本 2,因為它的功能更強大。

版本2

在 Firebase 安全規則版本 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>;
   }
  }
}

精細化運營

在某些情況下,將readwrite為更細粒度的操作很有用。例如,您的應用程序可能希望在文件創建時強制執行與文件刪除時不同的條件。

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

Denied :此規則拒絕以下請求,因為結果集可能包含contentType不是image/png文件:

網絡
filesRef = storage.ref().child("aFilenamePrefix");

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

Cloud Storage 安全規則中的規則根據每個查詢的潛在結果評估每個查詢,如果它可能返回客戶端無權讀取的文件,則該請求將失敗。訪問請求必須遵循您的規則設置的約束。

下一步

您可以加深對Firebase雲存儲安全規則的理解:

您可以探索特定於 Cloud Storage 的 Firebase 安全規則用例: