javascript - 为什么我的 Firebase 云函数不能使用 `allAuthenticatedUsers`?
问题描述
使用Firebase CLI部署 Firebase Functions 时,它们被配置为授予Cloud Functions Invoker权限allUsers
。通过这样的设置,下面的代码可以按预期运行。
Cloud Functions InvokerallAuthenticatedUsers
权限也可以授予. 但是,当我为 实现此更改时addMessage
,我只会UNAUTHENTICATED
使用下面的代码得到错误响应。
为什么不allAuthenticatedUsers
适用于此 Firebase 云功能?
注意:此问答是由Furkan Yurdakul发布的一个现已删除的问题的结果,该问题是关于为什么allAuthenticatedUsers
没有为他的 Firebase 应用程序使用他的 Firebase 可调用函数
firebase.auth().signInAnonymously() // for the sake of the MWE, this will normally be Facebook, Google, etc
.then((credential) => {
// logged in successfully, call my function
const addMessage = firebase.functions().httpsCallable('addMessage');
return addMessage({ text: messageText });
})
.then((result) => {
// Read result of the Cloud Function.
const sanitizedMessage = result.data.text;
alert('The sanitized message is: ' + sanitizedMessage);
})
.catch((error) => {
// something went wrong, keeping it simple for the MWE
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode === 'auth/operation-not-allowed') {
alert('You must enable Anonymous auth in the Firebase Console.');
} else {
console.error(error);
}
});
解决方案
简而言之,如果传递给 Cloud Function 的 ID 令牌代表一个 Google 帐户(通过Firebase或Google 本身使用 Google 登录),它就可以工作,否则就不行。
认为allAuthenticatedUsers
而allAuthenticatedGoogleUsers
不是allAuthenticatedFirebaseUsers
.
背景资料
对于与 Firebase 客户端 SDK 一起使用的可调用 Firebase 函数,您通常会授予allUsers
调用它的权限(默认设置Firebase CLI部署的函数)。
针对 Google Cloud Functions 的经过身份验证的有效客户端请求必须具有Authorization: Bearer ID_TOKEN
标头(首选)或?access_token=ID_TOKEN
. 这里,ID_TOKEN
是作为JWT登录的 Google 用户的 ID 令牌。
当 Firebase 客户端 SDK 调用 Callable Function 时,它们Authorization
会使用当前用户的ID 令牌为您设置标头(如果用户已登录,请点击此处)。这样做是为了可以在函数context
参数中使用用户的身份验证令牌onCall()
。但重要的是,Firebase 用户的 ID 令牌并不总是代表 Google 用户,这使其与allAuthenticatedUsers
.
正因为如此,您必须通过检查代码中的可调用函数context.auth
及其属性,如下所示。
export const addMessage = functions.https.onCall((data, context) => {
if (!context.auth) {
// Throwing a HttpsError so that the client gets the error details.
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called while authenticated.'
);
}
// a valid user is logged in
// do work
});
关于 403 禁止错误的附录
如果您的函数在部署后一直抛出 403 错误,这可能是因为您使用的是 Firebase CLI 的过时副本,如文档中突出显示的那样:
警告:使用低于 7.7.0 版本的任何 Firebase CLI 部署的新 HTTP 和 HTTP 可调用函数默认为私有,并在调用时引发 HTTP 403 错误。在部署任何新功能之前,明确公开这些功能或更新您的 Firebase CLI 。
推荐阅读
- python-3.x - tkinter:我如何使滚动条对框架的新大小做出反应
- react-native - 有没有办法在 React native 中单击按钮显示/隐藏功能组件
- bash - 如果两个字符串按长度匹配,则 Bash 比较
- javascript - 进度条jQuery百分比计数器不起作用
- python - ('关键字参数不理解:','W_regularizer')
- android - 如何在没有 android studio 的情况下安装颤振?
- docker-compose - 如何在 docker 中为 GetHistoryForKey() 设置 enableHistoryDatabase
- css - 如何在叠加层和文本中使用 z-index
- rest - Restful API 中的 HTTP GET 和对象数组查询
- ios - TableViewController 的 UItableView 如何添加到根视图控制器?