douren5490 2018-02-09 21:14
浏览 50
已采纳

Firebase数据库规则+身份验证无效

I can't seem to get my database rules to work, when they require authentication.

The user is logged in using JavaScript, and then the database is updated via PHP / REST request using firebase-php.

PHP:

$firebase = new \Firebase\FirebaseLib('https://AppNameGoesHere.firebaseio.com/');

$data = array(
   'field1' => $response_array['field1'],
   'field2' => $response_array['field2'],
   'field3' => $response_array['field3']
);

$firebase->set('users/' . $response_array['userID'], $data)

The $response_array is an array from an HTML form. $response_array['userID'] is the Firebase user uid.

These rules work (no auth):

{
  "rules": {
    "users": {
      "$uid": {
        ".read": true,
        ".write": true
      }
    }
  }
}

These, with auth, don't work:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth.uid === $uid",
        ".write": "auth.uid === $uid"
      }
    }
  }
}

Error:

{ "error" : "Permission denied" }

Any suggestions?

  • 写回答

1条回答 默认 最新

  • doulao5916 2018-02-13 04:36
    关注

    As Frank mentioned in the comments, you must call setToken() in order to authenticate all subsequent database reads/writes. To get that token from the client-side JavaScript and pass it to your PHP endpoint, you should use getIdToken like so:

    firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
      // Send token to your PHP backend via HTTPS
      // ...
    }).catch(function(error) {
      // Handle error
    });
    

    With that idToken value, it looks like you can pass that along to the firebase-php library's setToken function:

    ...
    $firebase->setToken(idToken)
    $firebase->set('users/' . $response_array['userID'], $data)
    

    As long as $response_array['userID'] matches up with the uid of whoever makes that request, you should no longer receive the Permission denied error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器