您可以使用 Firebase 安全性規則根據資料庫或儲存桶中的現有資料有條件地寫入新資料。您也可以編寫規則,透過根據正在寫入的新資料限制寫入來強制執行資料驗證。繼續閱讀以了解有關使用現有資料建立安全條件的規則的更多資訊。
在每個部分中選擇一個產品以了解有關資料驗證規則的更多資訊。
對新數據的限制
雲端Firestore
如果要確保不建立包含特定欄位的文檔,可以將該欄位包含在allow
條件中。例如,如果您想拒絕建立任何包含ranking
欄位的文檔,則可以在create
條件中禁止它。
service cloud.firestore {
match /databases/{database}/documents {
// Disallow
match /cities/{city} {
allow create: if !("ranking" in request.resource.data)
}
}
}
即時資料庫
如果您想確保包含某些值的資料不會新增至資料庫中,您可以將該值包含在規則中並禁止寫入。例如,如果您想要拒絕任何包含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')
}
}
雲端儲存
如果要確保不建立包含特定元資料的文件,可以將元資料包含在allow
條件中。例如,如果您想拒絕建立任何包含ranking
資料的文件,您可以在create
條件中禁止它。
service firebase.storage {
match /b/{bucket}/o {
match /files/{allFiles=**} {
// Disallow
allow create: if !("ranking" in request.resource.metadata)
}
}
}
使用 Firebase 安全規則中的現有數據
雲端Firestore
許多應用程式將存取控制資訊儲存為資料庫中文件的欄位。 Cloud Firestore 安全性規則可以根據文件資料動態允許或拒絕存取:
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;
}
}
}
即時資料庫
在即時資料庫中,使用.validate
規則來強制執行資料結構並驗證資料的格式和內容。規則在驗證.write
規則授予存取權限後執行.validate
規則。
.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
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];
迅速
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);
爪哇
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);
休息
# 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
雲端儲存
在評估規則時,您可能還需要評估正在上傳、下載、修改或刪除的檔案的元資料。這允許您創建複雜而強大的規則,執行諸如僅允許上傳特定內容類型的文件,或僅刪除大於特定大小的文件等操作。
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
物件屬性的完整清單。