最终目标:Angular客户端会收到一个有效期为一小时的令牌,以便从FireStore查询数据。
产生概念证明并学习如何使用自定义令牌的步骤:
1-我使用Firebase工具(https://console.firebase.google.com/project/firetestjimis/overview)在Firebase中创建了一个项目
2-我添加了Firestore数据库并创建了一个集合。我选择生产而不是测试,因为此POC出于安全原因。
3-我在Firebase / Authentication / Add User中手动添加了一个用户
4-我从添加的上述用户中复制了用户UID(以下使用)
5-我创建了一个非常简单的Firebase Cloud Function应用程序,以回复自定义令牌。基本上,我运行了firebase init,并将此代码添加到index.tx
import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";
export const getCustomToken = functions.https.onRequest((request, response) => {
if (admin.apps.length < 1) { //Checks if app already initialized
admin.initializeApp();
}
const uid = "UID mentioned above";
admin.auth().createCustomToken(uid)
.then(function (customToken) {
console.log(customToken.toString);
response.send(customToken);
})
.catch(function (error) {
console.log("Error creating custom token:", error);
});
});
我是通过关注other stackoverflow answer
达到此目的的6-我可以从https://us-central1-firetestjimis.cloudfunctions.net/getCustomToken
成功获得自定义令牌7-我可以成功地将此自定义令牌发布到https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken,并像这样返回idTken
{
"kind": "identitytoolkit#VerifyCustomTokenResponse",
"idToken": "eyJhbGciOiJSUzI1NiI ... .... aMorw",
"refreshToken": "AE0u-Ney9OJ04Z3xA7ACsmI1S637hXeuCTEdaEU9cxhhPnlwh-9q0X7QpSxVRIYdTdrTgXUbS9Q6yUdAWVeXzhGMiLLLHtwSWSoVSWnZs3Gp1Sb050tThNPQiSsSss8GkCigft3PTBkY4nIbRy3A5dA8FHCLbMYQSfKYqvu8To76UyMVCYONJOM",
"expiresIn": "3600",
"isNewUser": false
}
8-现在我要向Firestore集合投掷一个简单的文档
curl --location --request POST 'https://firestore.googleapis.com/v1/projects/firetestjimis/databases/(default)/documents/transfer' \
--header 'Authorization: Bearer /eyJhbGc ... ... iNaMorw' \
--header 'Content-Type: application/json' \
--data-raw '{
"fields": {
"id": {
"stringValue": "1"
},
"status": {
"stringValue": "fracasso"
}
}
}'
我得到这个错误:
{
"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"
}
}
所以我的主要问题是:https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken返回的idToken不是到达相关Firestore的有效令牌吗?
答案 0 :(得分:1)
标头中的ID令牌之前有一个正斜杠,该斜杠不应存在:
--header 'Authorization: Bearer /eyJhbGc ... ... iNaMorw' \
^