Xác thực dữ liệu

Bạn có thể sử dụng Firebase Security Rules để ghi dữ liệu mới theo điều kiện dựa trên dữ liệu hiện có trong cơ sở dữ liệu hoặc bộ chứa lưu trữ của bạn. Bạn cũng có thể viết các quy tắc thực thi dữ liệu bằng cách hạn chế việc ghi dựa trên dữ liệu mới đang được ghi. Đọc tiếp để tìm hiểu thêm về các quy tắc sử dụng dữ liệu hiện có để tạo điều kiện bảo mật.

Chọn một sản phẩm trong từng mục để tìm hiểu thêm về các quy tắc xác thực dữ liệu.

Các quy định hạn chế về dữ liệu mới

Cloud Firestore

Nếu bạn muốn đảm bảo rằng tài liệu có chứa một trường cụ thể đã tạo, bạn có thể đưa trường này vào điều kiện allow. Ví dụ: nếu bạn muốn từ chối tạo bất kỳ tài liệu nào có chứa trường ranking, bạn sẽ không cho phép lệnh đó trong điều kiện create.

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

Realtime Database

Nếu bạn muốn đảm bảo rằng dữ liệu chứa một số giá trị nhất định sẽ không được thêm vào vào cơ sở dữ liệu của mình, bạn sẽ đưa giá trị đó vào quy tắc và không cho phép nó viết. Ví dụ: nếu bạn muốn từ chối bất kỳ hoạt động ghi nào chứa ranking bạn sẽ không cho phép ghi đối với mọi tài liệu có giá trị 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

Nếu bạn muốn đảm bảo rằng một tệp chứa siêu dữ liệu cụ thể đã tạo, bạn có thể đưa siêu dữ liệu vào điều kiện allow. Ví dụ: nếu bạn muốn từ chối tạo bất kỳ tệp nào chứa siêu dữ liệu ranking, bạn sẽ không cho phép lệnh đó trong điều kiện create.

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

Sử dụng dữ liệu hiện có trong Firebase Security Rules

Cloud Firestore

Nhiều ứng dụng lưu trữ thông tin kiểm soát quyền truy cập dưới dạng trường trên các tài liệu trong cơ sở dữ liệu. Cloud Firestore Security Rules có thể linh động cho phép hoặc từ chối cấp quyền truy cập dựa trên tài liệu dữ liệu:

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

Biến resource tham chiếu đến tài liệu được yêu cầu, và resource.data là bản đồ tất cả các trường và giá trị được lưu trữ trong tài liệu. Để biết thêm thông tin về biến resource, hãy xem tài liệu tham khảo tài liệu.

Khi ghi dữ liệu, bạn có thể muốn so sánh dữ liệu đến với dữ liệu hiện có. Chiến dịch này cho phép bạn làm những việc như đảm bảo một trường không thay đổi, rằng một trường chỉ tăng thêm một hoặc giá trị mới ít nhất là một tuần trong tương lai. Trong trường hợp này, nếu bộ quy tắc của bạn cho phép thao tác ghi đang chờ xử lý, thì request.resource biến chứa trạng thái tương lai của tài liệu. Đối với các thao tác update chỉ sửa đổi một nhóm nhỏ các trường chứng từ, biến request.resource sẽ chứa trạng thái tài liệu đang chờ xử lý sau thao tác. Bạn có thể kiểm tra trường này trong request.resource để ngăn việc cập nhật dữ liệu không mong muốn hoặc không nhất quán:

   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

Trong Realtime Database, hãy dùng các quy tắc .validate để thực thi cấu trúc dữ liệu và xác thực định dạng và nội dung của dữ liệu. Rules chạy .validate quy tắc sau đó xác minh rằng quy tắc .write cấp quyền truy cập.

Các quy tắc .validate không phân tầng. Nếu bất kỳ quy tắc xác thực nào không thành công trên bất kỳ đường dẫn hoặc đường dẫn con trong quy tắc thì toàn bộ thao tác ghi sẽ bị từ chối. Ngoài ra, các định nghĩa xác thực chỉ kiểm tra các giá trị không rỗng, và sau đó bỏ qua mọi yêu cầu xoá dữ liệu.

Hãy cân nhắc các quy tắc .validate sau:

  {
    "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()"
        }
      }
    }
  }

Ghi các yêu cầu vào cơ sở dữ liệu với các quy tắc ở trên sẽ có nội dung sau kết quả:

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
Lưu ý: Sản phẩm Firebase này không dùng được trên mục tiêu App Clip (Đoạn video ứng dụng).
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
Lưu ý: Sản phẩm Firebase này không dùng được trên mục tiêu App Clip (Đoạn video ứng dụng).
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);
Kiến trúc chuyển trạng thái đại diện (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

Khi đánh giá quy tắc, bạn cũng nên đánh giá siêu dữ liệu của tệp đang được tải lên, tải xuống, sửa đổi hoặc xoá. Điều này cho phép bạn tạo các quy tắc phức tạp và hiệu quả để thực hiện những việc như chỉ cho phép các tệp có loại nội dung được tải lên hoặc chỉ các tệp lớn hơn kích thước nhất định đã bị xoá.

Đối tượng resource chứa các cặp khoá/giá trị với siêu dữ liệu tệp được hiển thị trong một Đối tượng Cloud Storage. Bạn có thể kiểm tra các thuộc tính này trên read hoặc write yêu cầu để đảm bảo tính toàn vẹn của dữ liệu. Đối tượng resource kiểm tra siêu dữ liệu trên các tệp hiện có trong bộ chứa Cloud Storage của bạn.

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

Bạn cũng có thể sử dụng đối tượng request.resource trong các yêu cầu write (chẳng hạn như tải lên, cập nhật siêu dữ liệu và xoá. Đối tượng request.resource nhận được siêu dữ liệu từ tệp sẽ được ghi nếu write được phép.

Bạn có thể sử dụng hai giá trị này để ngăn chặn những nội dung cập nhật không mong muốn hoặc không nhất quán hoặc để thực thi các quy tắc ràng buộc của ứng dụng, chẳng hạn như loại tệp hoặc kích thước tệp.

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

Danh sách đầy đủ các thuộc tính trong đối tượng resource có sẵn trong tài liệu tham khảo.