Firestore 自定义令牌

Firestore Custom Tokens

我正在尝试将自定义身份验证令牌与 firestore 结合使用。我正在使用 nodejs 通过以下代码生成令牌。

const admin = require('firebase-admin');
const serviceAccount = require('./ServiceAccountKey.json')

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

var uid = "some-uid";
var claim = {
  control: true
};
admin.auth().createCustomToken(uid, true)
  .then(function(customToken) {
    console.log(customToken)
  })
  .catch(function(error) {
    console.log("Error creating custom token:", error);
  });

当我 运行 它时,我得到了一个令牌。我拿那个令牌并尝试使用 https://firestore.googleapis.com/v1beta1/projects/example-project-5caa9/databases/(default)/documents/users 与 headers

Authorization:Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiY29udHJvbCI6dHJ1ZX0sInVpZCI6InNvbWUtdWlkIiwiaWF0IjoxNTI4MTQ0NzY3LCJleHAiOjE1MjgxNDgzNjcsImF1ZCI6Imh0dHBzOi8vaWRlbnRpdHl0b29sa2l0Lmdvb2dsZWFwaXMuY29tL2dvb2dsZS5pZGVudGl0eS5pZGVudGl0eXRvb2xraXQudjEuSWRlbnRpdHlUb29sa2l0IiwiaXNzIjoiZmlyZWJhc2UtYWRtaW5zZGsteG9jMDRAZXhhbXBsZS1wcm9qZWN0LTVjYWE5LmlhbS5nc2VydmljZWFjY291bnQuY29tIiwic3ViIjoiZmlyZWJhc2UtYWRtaW5zZGsteG9jMDRAZXhhbXBsZS1wcm9qZWN0LTVjYWE5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0.Bjl6VY5CZKIpNyCayROWr_ZBSRmo11hiwtnx_cbbw2Ggk3J2x0Ml2OkpXhU-vAD6Q53fCZwGgXeCdxnsXw0lr55cJH3Q6J7gitzQoRnfJgUX9Dv1gbI90OWashxMmxtzPIpwgSnfBv61mkdv9ZVrF8o362mQBx_LUQzvGgVPEN9_9UNCH7peOS4KYr_YRMpCQVem0XMNh9WKlyBZuScjHpY6dZZhXqOHda0W9-MNAfvQ-D0pt-osq4ty-D_WYk6CjLNmxzvHoZeoIk1YShJM4Mpyec3lXFcCXNYG2c3_r2tskTB0LF7Fc7Bg5XuJwlrAzHrnRis6iZFCx8sqH1b-Zg

得到以下JSON.

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

我的规则如下

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

您无法使用自定义令牌直接访问 REST API。您需要使用自定义令牌登录,并获取 ID 令牌。有两种方法可以做到这一点:

然后您可以使用生成的 ID 令牌访问 Firestore REST API:

https://firebase.google.com/docs/firestore/use-rest-api#working_with_firebase_id_tokens