sam*_*man 5 javascript firebase firebase-authentication google-cloud-functions
使用 Firebase CLI部署 Firebase Functions 时,将对其进行配置,以便向授予Cloud Functions InvokerallUsers权限。通过这样的设置,下面的代码可以按预期运行。
还可以将Cloud Functions Invoker权限授予allAuthenticatedUsers. 但是,当我对 实施此更改时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);
}
});
Run Code Online (Sandbox Code Playgroud)
sam*_*man 13
简而言之,如果传递给 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是已登录 Google 用户的 ID 令牌(JWT )。
当 Firebase 客户端 SDK 调用可调用函数时,它们会使用当前用户的ID 令牌Authorization为您设置标头(如果用户已登录,请在此处)。这样做是为了可以在函数的参数中使用用户的身份验证令牌。但重要的是,Firebase 用户的 ID 令牌并不总是代表 Google 用户,这使得它与.contextonCall()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
});
Run Code Online (Sandbox Code Playgroud)
如果您的函数在部署后始终抛出 403 错误,这可能是因为您使用的是过时的 Firebase CLI 副本,如文档中突出显示的:
注意:使用任何低于版本 7.7.0 的 Firebase CLI 部署的新 HTTP 和 HTTP 可调用函数默认情况下都是私有的,并且在调用时会引发 HTTP 403 错误。在部署任何新函数之前,明确公开这些函数或更新您的 Firebase CLI 。
| 归档时间: |
|
| 查看次数: |
1681 次 |
| 最近记录: |