FCM not working in Firebase Cloud Function because admin sdk authentication-error

Viewed 130

I am currently trying to send FCM using Firebase Cloud Function in the Flutter WEB environment. But it doesn't work very well

My Problem

My index.js Code

/* eslint-disable max-len */
const admin = require("firebase-admin");
const {applicationDefault} = require("firebase-admin/app");
const functions = require("firebase-functions");
const cors = require("cors")({origin: true});
admin.initializeApp({credential: applicationDefault(), databaseURL: "https://<PROJECT-ID>.firebaseio.com"});
const messaging = admin.messaging();

exports.sendNoti = functions.runWith({
  allowInvalidAppCheckToken: true}).https.onRequest(async (req, res) => {
  cors(req, res, async () =>{
    if (res.app == undefined) {
      console.log("App Check failed-precondition / The function must be called from an App Check verified app.");
    }
    console.log(res.app);
    try {
      await messaging.sendToDevice(req.body.data.targetDevices, {
        notification: {
          title: req.body.data.messageTitle,
          body: req.body.data.messageBody,
        },
      });
      res.set("Access-Control-Allow-Origin", "*");
      res.status(200).send({"status": "success", "data": "GOOD"});
      return true;
    } catch (ex) {
      console.log(ex);
      res.set("Access-Control-Allow-Origin", "*");
      res.status(200).send({"status": "fail", "data": ex});
      return ex;
    }
  });
});

Error Message

{errorInfo: {code: messaging/authentication-error, message: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "HTML CODE ". Status code: 401.}, codePrefix: messaging}

My Try

  1. credential: admin.credential.applicationDefault(),
  2. credential: admin.credential.cert("service.json"),
  3. Use OnCall function
  4. Use AppCheck
0 Answers
Related