資料驗證

您可以使用 Firebase Security Rules,根據現有資料有條件地寫入新資料 資料庫或儲存空間值區中的資源您也可以編寫規則來強制執行資料 限制寫入作業,以根據寫入的新資料限制寫入作業。請繼續閱讀 ,進一步瞭解使用現有資料建立安全性條件的規則。

請在各個部分中選取產品,進一步瞭解資料驗證規則。

新資料相關限制

Cloud Firestore

如何確保含有特定欄位的文件不會 您可以在 allow 條件中加入該欄位。舉例來說 要拒絕建立任何包含 ranking 欄位的文件, 您會禁止在 create 條件下使用。

  service cloud.firestore {
    match /databases/{database}/documents {
      // Disallow
      match /cities/{city} {
        allow create: if !("ranking" in request.resource.data)
      }
    }
  }

Realtime Database

如要確保系統不會新增包含特定值的資料 請在規則中加入該值,並禁止 寫入。舉例來說,如果您要拒絕任何含有 ranking 的寫入作業 值,不允許任何含有 ranking 值的文件寫入。

  {
    "rules": {
      // Write is allowed for all paths
      ".write": true,
      // Allows writes only if new data doesn't include a `ranking` child value
      ".validate": "!newData.hasChild('ranking')
    }
  }

Cloud Storage

如要確定含有特定中繼資料的檔案 此時您可以在 allow 條件中加入中繼資料。舉例來說 您要拒絕建立任何包含 ranking 中繼資料的檔案 您會禁止在 create 條件下使用。

  service firebase.storage {
    match /b/{bucket}/o {
      match /files/{allFiles=**} {
      // Disallow
        allow create: if !("ranking" in request.resource.metadata)
      }
    }
  }

在「Firebase Security Rules」中使用現有資料

Cloud Firestore

許多應用程式會將存取權控管資訊儲存為資料庫中文件的欄位。 Cloud Firestore Security Rules 可根據文件動態允許或拒絕存取 資料:

  service cloud.firestore {
    match /databases/{database}/documents {
      // Allow the user to read data if the document has the 'visibility'
      // field set to 'public'
      match /cities/{city} {
        allow read: if resource.data.visibility == 'public';
      }
    }
  }

resource 變數參照要求的文件,resource.data 是 文件中所有欄位和值的對應。如要 resource 變數的相關資訊,請參閱參考資料 說明文件

寫入資料時,您可能會想比較傳入的資料與現有資料。這個 可讓您確保欄位沒有變更 或新值至少在一週之後。 在這種情況下,如果您的規則集允許待處理寫入,request.resource 變數包含文件的未來狀態。僅適用於update作業 修改文件欄位的子集,request.resource 變數就會 包含作業完成後待處理的文件狀態。您可以勾選 request.resource 中的值,以避免發生不必要的資料更新或不一致的資料更新的情況:

   service cloud.firestore {
     match /databases/{database}/documents {
      // Make sure all cities have a positive population and
      // the name is not changed
      match /cities/{city} {
        allow update: if request.resource.data.population > 0
                      && request.resource.data.name == resource.data.name;
      }
    }
  }

Realtime Database

Realtime Database 中,使用 .validate 規則強制執行資料結構並驗證 資料的格式與內容Rules會在以下日期後執行 .validate 項規則: 驗證 .write 規則是否已授予存取權。

.validate 規則不會串聯。如有任何驗證規則失敗 會拒絕整個寫入作業。 此外,驗證定義只會檢查非空值,且 隨後就會忽略所有刪除資料的要求。

請考慮以下 .validate 規則:

  {
    "rules": {
      // write is allowed for all paths
      ".write": true,
      "widget": {
        // a valid widget must have attributes "color" and "size"
        // allows deleting widgets (since .validate is not applied to delete rules)
        ".validate": "newData.hasChildren(['color', 'size'])",
        "size": {
          // the value of "size" must be a number between 0 and 99
          ".validate": "newData.isNumber() &&
                        newData.val() >= 0 &&
                        newData.val() <= 99"
        },
        "color": {
          // the value of "color" must exist as a key in our mythical
          // /valid_colors/ index
          ".validate": "root.child('valid_colors/' + newData.val()).exists()"
        }
      }
    }
  }

使用上述規則將要求寫入資料庫會產生下列影響 結果:

JavaScript
var ref = db.ref("/widget");

// PERMISSION_DENIED: does not have children color and size
ref.set('foo');

// PERMISSION DENIED: does not have child color
ref.set({size: 22});

// PERMISSION_DENIED: size is not a number
ref.set({ size: 'foo', color: 'red' });

// SUCCESS (assuming 'blue' appears in our colors list)
ref.set({ size: 21, color: 'blue'});

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child('size').set(99);
Objective-C
注意:這項 Firebase 產品不適用於 App Clip 目標。
FIRDatabaseReference *ref = [[[FIRDatabase database] reference] child: @"widget"];

// PERMISSION_DENIED: does not have children color and size
[ref setValue: @"foo"];

// PERMISSION DENIED: does not have child color
[ref setValue: @{ @"size": @"foo" }];

// PERMISSION_DENIED: size is not a number
[ref setValue: @{ @"size": @"foo", @"color": @"red" }];

// SUCCESS (assuming 'blue' appears in our colors list)
[ref setValue: @{ @"size": @21, @"color": @"blue" }];

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
[[ref child:@"size"] setValue: @99];
Swift
注意:這項 Firebase 產品不適用於 App Clip 目標。
var ref = FIRDatabase.database().reference().child("widget")

// PERMISSION_DENIED: does not have children color and size
ref.setValue("foo")

// PERMISSION DENIED: does not have child color
ref.setValue(["size": "foo"])

// PERMISSION_DENIED: size is not a number
ref.setValue(["size": "foo", "color": "red"])

// SUCCESS (assuming 'blue' appears in our colors list)
ref.setValue(["size": 21, "color": "blue"])

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child("size").setValue(99);
Java
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("widget");

// PERMISSION_DENIED: does not have children color and size
ref.setValue("foo");

// PERMISSION DENIED: does not have child color
ref.child("size").setValue(22);

// PERMISSION_DENIED: size is not a number
Map<String,Object> map = new HashMap<String, Object>();
map.put("size","foo");
map.put("color","red");
ref.setValue(map);

// SUCCESS (assuming 'blue' appears in our colors list)
map = new HashMap<String, Object>();
map.put("size", 21);
map.put("color","blue");
ref.setValue(map);

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child("size").setValue(99);
REST
# PERMISSION_DENIED: does not have children color and size
curl -X PUT -d 'foo' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# PERMISSION DENIED: does not have child color
curl -X PUT -d '{"size": 22}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# PERMISSION_DENIED: size is not a number
curl -X PUT -d '{"size": "foo", "color": "red"}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# SUCCESS (assuming 'blue' appears in our colors list)
curl -X PUT -d '{"size": 21, "color": "blue"}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# If the record already exists and has a color, this will
# succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
# will fail to validate
curl -X PUT -d '99' \
https://docs-examples.firebaseio.com/rest/securing-data/example/size.json

Cloud Storage

評估規則時,建議您評估檔案的中繼資料 上傳、下載、修改或刪除這可讓您 複雜且功能強大的規則,例如僅允許符合特定條件的檔案 要上傳的內容類型,或只上傳大於特定大小的檔案 已刪除。

resource 物件包含鍵/值組合,以及會顯示於 Cloud Storage 物件。如要查看這些屬性,請前往 read 或 用於確保資料完整性的 write 要求。resource 物件會檢查中繼資料 套用至 Cloud Storage 值區中的現有檔案。

  service firebase.storage {
    match /b/{bucket}/o {
      match /images {
        match /{allImages=**} {
          // Allow reads if a custom 'visibility' field is set to 'public'
          allow read: if resource.metadata.visibility == 'public';
        }
      }
    }
  }

您也可以在 write 要求中使用 request.resource 物件 (例如 上傳、中繼資料更新和刪除等內容request.resource 物件會取得 如果允許使用 write,則系統將寫入該檔案的中繼資料。

你可以使用這兩個值來避免發生不必要的更新或不一致的更新 或強制執行應用程式限制,例如檔案類型或大小

  service firebase.storage {
    match /b/{bucket}/o {
      match /images {
        // Cascade read to any image type at any path
        match /{allImages=**} {
          allow read;
        }

        // Allow write files to the path "images/*", subject to the constraints:
        // 1) File is less than 5MB
        // 2) Content type is an image
        // 3) Uploaded content type matches existing content type
        // 4) File name (stored in imageId wildcard variable) is less than 32 characters
        match /{imageId} {
          allow write: if request.resource.size < 5 * 1024 * 1024
                       && request.resource.contentType.matches('image/.*')
                       && request.resource.contentType == resource.contentType
                       && imageId.size() < 32
        }
      }
    }
  }

如需 resource 物件的完整屬性清單,請參閱 請參閱參考說明文件