我想通过 firebasefunctions:shell
作为经过身份验证的 usr 测试 onCall 函数
我已经尝试了许多来自 https://firebase.google.com/docs/functions/local-emulator#invoke_https_functions 的调用组合
以及下载和设置 GOOGLE_APPLICATION_CREDENTIALS
环境变量
我的函数如下所示:
exports.sendMessage = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
}
// Other logic
}
一旦部署并从我的 ios 应用程序中点击它就可以正常工作,但我无法让它在 shell 中运行。
以下命令将实际调用该函数:
sendMessage.post({headers: {'content-type' : 'application/json'},body: JSON.stringify({data: {'messageId':'test'} }) })
并返回
从函数收到的响应:400,{“error”:{“status”:“FAILED_PRECONDITION”,“message”:“必须在经过身份验证时调用该函数。”}}
这是正确的,但我现在想要一个经过身份验证的用户。当我尝试像文档建议的那样添加身份验证时:
sendMessage('data', {auth:{uid:'USERUID'}}).post({headers: {'content-type' : 'application/json'},body: JSON.stringify( {data: {'messageId':'test'} }) })
我最终得到错误发送请求:错误:未定义身份验证机制
如果我尝试遵循此页面上的授权 header https://firebase.google.com/docs/functions/callable-reference像这样:
sendMessage.post({headers: {'Authorization': '承载 USERUID', 'content-type' : 'application/json'},body: JSON.stringify({data: {'messageId': '测试'} }) })
我回来了:
从函数收到的响应:401,{"error":{"status":"UNAUTHENTICATED","message":"Unauthenticated"}}
如何以经过身份验证的用户身份发送请求?
相关链接 How to test `functions.https.onCall` firebase cloud functions locally?
最佳答案
根据文档,授权 header 需要身份验证 ID token ,而不是用户 ID。您必须以某种方式生成一个 token 并将其传递给该函数。然后,可调用函数将验证该 token 并通过 context.auth
向该函数提供用户 ID。
看起来您可以使用 Firebase Auth REST API获得这些代币之一。或者,您可以在使用 Firebase Auth 客户端库的客户端应用中生成一个,记录它并复制其值,然后使用它直到过期(1 小时)。
关于firebase - 如何以经过身份验证的用户身份在函数 :shell 中测试 onCall 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282624/