Search code examples
google-cloud-functionsfirebase-cloud-messaging

Using Firebase Cloud Messaging from a Google Cloud Function


How can FCM be used from a Google Cloud Function (CF) (not a Firebase Cloud Function)? The main problem seems to be authentication/permissions. Google's documentation has bamboozled me yet again.

FCM is being used by one of our GAE applications. However the initialization of Firebase FCM from a CF seems to differ. Our GAE app initialize Firebase like this (upon initialization).

FileInputStream serviceAccount = new FileInputStream( "WEB-INF/mywebappfirebasekey.json" );

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials( GoogleCredentials.fromStream( serviceAccount ) )
.setDatabaseUrl( "https://my-firebase-project.firebaseio.com" )
.build();

I'm not sure how to read the Firebase JSON file in CF like we do with the GAE app or even if this way of initializing will work in a CF.

Instead I've adjusted IAM in our Firebase project (via cloud console) to provide access to our CF, using the service account. The principal is the service account of the CF project.

enter image description here

I've also done the converse. Using cloud console, I've added a Firebase role to our CF service account.

enter image description here

All of this makes no difference. CF logs show this error when trying to send a message via Firebase.

Error:Permission 'cloudmessaging.messages.create' denied on resource '//cloudresourcemanager.googleapis.com/projects/firebase-project-id' (or it may not exist).


Solution

  • Firebase Cloud Messaging Admin does not have permission for cloudmessaging.messages.create. In order to add this permission, use one of the following roles:

    1. Firebase SDK Provisioning Service Agent (roles/firebase.sdkProvisioningServiceAgent)

    2. Firebase Admin SDK Administrator Service Agent (roles/firebase.sdkAdminServiceAgent)

    3. Firebase Grow Admin (roles/firebase.growthAdmin)

    4. Firebase Admin (roles/firebase.admin)

    You may refer to this documentation: IAM basic and predefined roles reference