api - Firebase 通过 REST API PHP CURL 获取数据

标签 api rest firebase

尝试通过 PHP cURL 进行简单的读取。如果我的安全规则允许每个人进入,我就可以成功读取我的数据

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

但是,如果我将读/写限制为特定用户名,例如

{
  "rules": {
    ".read": "auth.username == 'admin'",
    ".write": "auth.username == 'admin'"
  }
}

我的许可被拒绝。

代码如下...

require('JWT.php');
$secret = 'MY_FIREBASE_SECRET';
$data = array('username' => 'admin');
$token = JWT::encode($data, $secret);

$url = "https://MY_FIREBASE.firebaseio.com/messages.json?auth=$token";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url
));
$response = curl_exec($curl);

值得注意的是,如果我只使用 FB key 而不是 URL 中的 token ,我就能够成功读取数据 (auth=$secret)。我还成功地测试了使用“自定义身份验证”在 Forge 模拟器中读取数据,例如{'用户名':'管理员'}

我正在使用 PHP JWT 库:https://github.com/luciferous/jwt/blob/master/JWT.php

不确定我的权限是否被拒绝,因为我的 cURL 调用不正确或者我没有正确构建 token 。我尝试过通过 cURL 使用 POST 和 GET,但得到了相同的结果。

如有任何建议,我们将不胜感激...


感谢安德鲁的快速回复。我尝试了你的建议。不幸的是,我仍然收到“许可被拒绝”的消息。这是我更新的代码...

require('JWT.php');
$secret = 'my-secret';
$user = array( 'v' => 0, 'iat' => time(), 'd' => array('username' => 'admin', 'type' => 'admin', 'fullname' => 'Administrator'));
$token = JWT::encode($user, $secret);
$curl = curl_init();
$url = "https://myfirebase.firebaseio.com/messages.json?auth=$token";
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url
));
$response = curl_exec($curl);
curl_close($curl);
  • 我确实通过将数据的 .read 规则更改为 “auth != null” - 但这似乎不太安全......

作为引用,我们的数据结构很简单

+ myfirebase
            + messages
                       - 000001 = "this is the 1st test message"
                       - 000002 = "this is the 2nd test message"

顺便说一句:我们的应用程序将只有 1 个用户读取/写入数据。如果我无法让 token 发挥作用...是否有更好的方法通过 REST API 来验证调用,而无需在 URL 中传递我们的 key ?例如&auth='我的 secret '

最佳答案

Firebase JWT 有一些此处缺失的结构。这里有关于这些身份验证 token 中应包含的内容的详细说明: https://www.firebase.com/docs/security/jwt-auth-token-format.html

这是一个具有适当结构的片段。

require_once('JWT.php');

$fbSecret = 'your-secret';
$user = array( 'v' => 0, 'iat' => <timestamp>, 
  'd' => array('username' => 'jimbob', 'type' => 'admin',\
    'fullname' => 'Jim Bob')
  );
$token = JWT::encode($user, $fbSecret);

请注意,“d”字段包含实际的有效负载。 “v”和“iat”也是必需的。 “iat”应该是自纪元以来的秒数(它是 (new Date()).getTime() 在 Javascript 中返回的数字)。

关于api - Firebase 通过 REST API PHP CURL 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073328/

相关文章:

javascript - 在 Angular View 中显示谷歌地图的间歇性问题

Spring Rest Controller 跟踪实体 View 计数

javascript - 在 firebase 中将数据存储到多个引用的最有效方法是什么?

java - 从rest api下载文件给了我一些垃圾值

django - 在 Django rest 框架中转换 `ManyToManyField`

firebase - 是否重复使用 FCM token ?

firebase - 通过 GET 方法将 Cloud Functions 用于 Firebase HTTPS

php - 使用 youtube api v3 验证视频是否存在

javascript - 防止 Angular 网站上未经授权的用户在被重定向到登录之前瞬间看到网站的最佳方法?

api - 有什么方法可以让我的 meteor 应用加载时播放youtube视频,并知道视频何时停止播放,以便我播放下一个?