【问题标题】:How to test an onCall function as an authenticated user in the functions:shell如何在函数中以经过身份验证的用户身份测试 onCall 函数:shell
【发布时间】:2019-02-16 08:29:50
【问题描述】:

我想通过firebase functions:shell 作为经过身份验证的 usr 来测试 onCall 函数

我尝试了很多来自https://firebase.google.com/docs/functions/local-emulator#invoke_https_functions 的调用组合 以及下载和设置GOOGLE_APPLICATION_CREDENTIALS env var

我的函数如下所示:

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'} }) })

然后返回

RESPONSE RECEIVED FROM FUNCTION: 400, {“error”:{“status”:“FAILED_PRECONDITION”,“message”:“The function must be called while authenticated.“}}

这是正确的,但我现在想要一个经过身份验证的用户。当我尝试像文档推荐的那样添加身份验证时:

sendMessage('data', {auth:{uid:'USERUID'}}).post({headers: {'content-type' : 'application/json'},body: JSON.stringify({data: {'messageId':'test'} }) })

我最终得到ERROR SENDING REQUEST: Error: no auth mechanism defined

如果我尝试遵循此页面上的授权标头https://firebase.google.com/docs/functions/callable-reference,如下所示:

sendMessage.post({headers: {'Authorization': 'Bearer USERUID', 'content-type' : 'application/json'},body: JSON.stringify({data: {'messageId':'test'} }) })

我回来了:

从函数接收到响应:401,{"error":{"status":"UNAUTHENTICATED","message":"Unauthenticated"}}

您如何以经过身份验证的用户身份发送请求?

相关链接 How to test `functions.https.onCall` firebase cloud functions locally?

【问题讨论】:

    标签: firebase firebase-authentication google-cloud-functions


    【解决方案1】:

    根据文档,授权标头需要身份验证 ID 令牌,而不是用户 ID。您必须以某种方式生成令牌并将其传递给函数。然后,可调用函数将验证该令牌并通过 context.auth 将用户 ID 提供给该函数。

    您似乎可以使用Firebase Auth REST API 来获取这些令牌之一。或者,您可以在使用 Firebase Auth 客户端库的客户端应用中生成一个,记录并复制其值,然后使用它直到过期(1 小时)。

    【讨论】:

    • 不错,非常好。您能否在 firebase shell 中编写一个示例,调用带有数据结构的“可调用”以进行身份​​验证?即可调用的第二个参数。我在任何地方都找不到任何例子...... :(
    • 希望看到一个用于测试可调用函数的身份验证示例,我发现文档对此有点了解:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 2021-01-10
    • 2020-11-15
    • 2016-01-17
    • 2019-06-30
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多