אימות נתונים

אפשר להשתמש בפונקציה 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 הזה לא זמין ביעד 'קליפ של אפליקציה'.
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 הזה לא זמין ביעד של קטע מקדים לאפליקציה.
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';
        }
      }
    }
  }

אפשר גם להשתמש באובייקט 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 זמינה ב מסמכי עזר.