簡體   English   中英

如何從應用了安全規則的 firebase 實時數據庫中查詢

[英]how to query from firebase realtime database with security rules applied

我已經為這個問題設置了 firebase 實時數據庫的基本安全規則。 在我跳到問題之前,我已經使用 GetX 創建了一個 Flutter 移動應用程序,並且我還安裝了http: ^0.13.4插件用於查詢。

這是我設置安全規則的方式

{
  "rules":{
    ".read" : "auth.uid !== null && auth.token.email_verified == true",
    ".write" : "auth.uid !== null"    
  }
}

所以基本上,我希望用戶在經過身份驗證和 email 驗證后能夠讀取數據。

對於寫入規則,僅當用戶通過身份驗證並且 isAdmin 的自定義聲明設置為 true 時。 對於isAdmin,我不知道要在安全規則中設置。

是這樣的嗎?

"auth.uid !== null && root.child('isAdmin').val() == true" 

無論如何,我的問題是如何在客戶端使用 http 插件進行查詢? 這是 GET 查詢的示例

Uri url = Uri.parse('URL HERE with /.json file');

getIPTIdAndName() async {
  iptList.value = [];
  await http.get(url, headers: {"Authorization": FirebaseAuth.instance.currentUser!.uid}).then(
    (value) {
      var response = json.decode(value.body) as List<dynamic>;
      for (var i = 0; i < response.length; i++) {
        iptList.add({
          "iptIndex": i,
          "iptId": response[i]['id'],
          "iptName": response[i]['name']
        });
      }
      iptList.refresh();
    },
  );
}

如何查詢是否設置了安全規則?

更新代碼

//create a function inside authController and called it inside the javascript
Future<String> getIdToken() async{
  return await FirebaseAuth.instance.currentUser!.getIdToken();
}

getIPTIdAndName() async {
  iptList.value = [];

  Uri url = Uri.parse('$urlString?auth=${await auth.getIdToken()}');

  await http.get(url).then(
    (value) {
      var response = json.decode(value.body) as List<dynamic>;
      for (var i = 0; i < response.length; i++) {
        iptList.add({
          "iptIndex": i,
          "iptId": response[i]['id'],
          "iptName": response[i]['name']
        });
      }
      iptList.refresh();
    },
  );
}

//security rules
{
  "rules":{
    ".read" : "auth != null && auth.token.email_verified == true",
    ".write" : "auth != null && auth.token.admin == true"    
  }
}

如果 Firebase 接受 UID 作為 URL 參數,那將是非常不安全的,因為任何人都可以傳遞您的 UID 並獲得對您數據的訪問權限。

相反,您應該傳遞 ID 令牌,它是整個用戶數據的編碼版本,然后 Firebase 服務器可以解碼並將auth變量傳遞給您的規則。

有關詳細信息,請參閱有關對 Firebase 實時數據庫的 REST API 請求進行身份驗證的文檔,特別是有關使用 ID 令牌進行身份驗證的部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM