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 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了