RN Firebase Realtime DB 身份验证令牌负载

RN Firebase Realtime DB auth token payload

使用react-native-firebase:4.3.x

我可以连接到 RealtimeDB,我们需要安全设置 rules

但是通过 docs 我无法找到连接到 firebase 时如何设置 Auth 令牌有效负载 的位置。它所要做的就是连接到数据库调用以下内容:

db = firebase.database();

没有参数或任何东西。我要使用 firebase.auth()?

Short answer: Our whole approach on Firebase RealtimeDB's ruleset was incorrect from the beginning; we had done the rules without understanding Firebase Auth and its tie in with RealtimeDB. We had setup, rules based on uid and RealtimeDB only, storing some random token on RealtimeDB hoping we could somehow pass the token on auth payload to the user.

Long answer: As stated on Firebase's own Database Security docs Database Rules directly uses Firebase Authentication.

From then on, implemented Custom authentication from Authentication RNFirebase.io

client side:

let postLogin = (userCredentials) => {
  db = firebase.database();
  //...do stuff
}

firebase
  .auth()
  .signInAndRetrieveDataWithCustomToken(token)
  .then(postLogin);

firebase console: Project Settings -> Service Accounts -> Generate new private key. which generates json formatted firebase private key and some identifier values. Import that in whatever library you're using on server-side in our case kreait/firebase-php

Do not enable anonymous authentication, that would defeat the purpose.

php using kreait/firebase.php:

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

$serviceAccount = ServiceAccount::fromJsonFile($pathToJson);
$firebase = (new Factory())
  ->withServiceAccount($serviceAccount)
  ->create();

$token = (string) $firebase->getAuth()->createCustomToken($uid, $payload)

I did not need to be aware of payload on client side. It is passed through client side in the signed JWToken.