אתה יכול להשתמש בכללי האבטחה של Firebase כדי לכתוב נתונים חדשים על בסיס נתונים קיימים במסד הנתונים או בדלי האחסון שלך. אתה יכול גם לכתוב כללים האוכפים אימות נתונים על ידי הגבלת כתיבה על סמך הנתונים החדשים שנכתבים. המשך לקרוא כדי ללמוד עוד על כללים המשתמשים בנתונים קיימים כדי ליצור תנאי אבטחה.
בחר מוצר בכל חלק כדי ללמוד עוד על כללי אימות נתונים.
הגבלות על נתונים חדשים
Cloud 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
Cloud 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
כדי לאכוף מבני נתונים ולאמת את הפורמט והתוכן של הנתונים. כללים מפעילים כללי .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
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);
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);
מנוחה
# 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';
}
}
}
}
ניתן להשתמש באובייקט request.resource
גם בבקשות write
(כגון העלאות, עדכוני מטא נתונים ומחיקות. האובייקט 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
זמינה בתיעוד ההפניה .