I will explain how to check the AppCheck token in Firebase Cloud Functions and call Cloud Functions by putting the AppCheck token in the header in the app as follows.
Flutter App, FirebaseAppCheck Token in the header and call Cloud Functions.
final appCheckToken = await FirebaseAppCheck.instance.getToken();
if (appCheckToken != null) {
final response = await http.get(
Uri.parse("https://<Cloud Functions URI>/?text=addmessage3app"),
headers: {"X-Firebase-AppCheck": appCheckToken},
);
print('test');
} else {
// Error: couldn't get an App Check token.
}
Firebase Cloud Functions Backend (in Python)
- In @https_fn.on_request, set enforce_app_check=True.
- Get the token of X-Firebase-AppCheck from header and verify_token from app_check.
- verify_token in app_check and call
- If no exception is thrown, ok
Here is the code.
from firebase_admin import app_check
import jwt
@https_fn.on_request(
# Requests with invalid App Check tokens will be rejected with HTTP error 401.
enforce_app_check=True
)
def my_api3(req: https_fn.Request) -> https_fn.Response:
app_check_token = req.headers.get("X-Firebase-AppCheck", default="")
try:
app_check_claims = app_check.verify_token(app_check_token)
# If verify_token() succeeds, okay to continue to route handler.
except (ValueError, jwt.exceptions.DecodeError):
return https_fn.Response("Not verified", status=401)
# my code
original = req.args.get("text")
if original is None:
return https_fn.Response("No text parameter provided", status=400)
firestore_client: google.cloud.firestore.Client = firestore.client()
# Push the new message into Cloud Firestore using the Firebase Admin SDK.
_, doc_ref = firestore_client.collection("messages").add(
{"original": original}
)
# Send back a message that we've successfully written the message
return https_fn.Response(f"Message with ID {doc_ref.id} added!")
Test,
I added the FirebaseAppCheck token in Flutter and checked that CloudFunctions works properly, and conversely, when I called it without FirebaseAppCheck token in Flutter App, I checked that the 401 error code I defined is responded.
I used PostMan to test CloudFunctions by reusing the token I created and used in FlutterApp. See the attached picture.
