Why Can't I Use `allauthenticatedusers` For My Firebase Cloud Function?
Solution 1:
Simply put, if the ID token passed to a Cloud Function represents a Google account (that used Google Sign-In through Firebase or Google itself), it works, otherwise, it doesn't.
Think of allAuthenticatedUsers
as allAuthenticatedGoogleUsers
instead of allAuthenticatedFirebaseUsers
.
Background Information
For Callable Firebase Functions used with the Firebase Client SDKs, you will normally grant allUsers
the permission to call it (the default setting Firebase CLI deployed functions).
A valid authenticated client request for a Google Cloud Functions must have an Authorization: Bearer ID_TOKEN
header (preferred) or ?access_token=ID_TOKEN
. Here, ID_TOKEN
is a signed-in Google user's ID token as a JWT.
When Firebase Client SDKs call a Callable Function, they set the Authorization
header for you with the current user's ID token (if the user is signed in, here). This is done so that the user's authentication token can be used in the context
parameter of onCall()
functions. Importantly though, a Firebase user's ID token doesn't always represent a Google user which makes it incompatible with allAuthenticatedUsers
.
Because of this, you will have to gate your callable function in your code by checking context.auth
and it's properties like below.
exportconst addMessage = functions.https.onCall((data, context) => {
if (!context.auth) {
// Throwing a HttpsError so that the client gets the error details.thrownew functions.https.HttpsError(
'failed-precondition',
'The function must be called while authenticated.'
);
}
// a valid user is logged in// do work
});
Addendum on 403 Forbidden Errors
If your function is consistently throwing a 403 error after being deployed, this is likely because you are using an outdated copy of the Firebase CLI, as highlighted in the documentation:
Caution: New HTTP and HTTP callable functions deployed with any Firebase CLI lower than version 7.7.0 are private by default and throw HTTP 403 errors when invoked. Either explicitly make these functions public or update your Firebase CLI before you deploy any new functions.
Post a Comment for "Why Can't I Use `allauthenticatedusers` For My Firebase Cloud Function?"