0

I am sending a POST request to Firebase Cloud Messaging servers using the endpoint https://fcm.googleapis.com/v1/projects/{PROJECT_NAME}/messages:send so as to send notifications to my app. The problem is i am getting an error 401, AUTHENTICATION ERROR. I have gone through their doc https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send?apix=true many times and i can't seem to understand why i am getting this error. I tried testing the endpoint with the Google API explorer on the page and it works fine. Notification is sent to my app. However, sending this same POST request in my code with volley fails with the follow error, in JSON:

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

Here's what i did:

val FCM_POST = "https://fcm.googleapis.com/v1/projects/${Constants.PROJECT_NAME}/messages:send"

val map = mapOf("message" to
               mapOf("notification" to
                   mapOf("title" to "test title",
                          "body" to "test body")),
               "topic" to "testTopic")

    val request = object : JsonObjectRequest(
            Method.POST,
            FCM_POST,
            JSONObject(map), {
        showDialog.log(TAG, "sendMedicalTipsNotification response: $it")
    }, {
        val networkResponse = it.networkResponse
        if (networkResponse?.data != null) {
            val jsonError = String(networkResponse.data)
            try {
                val jsonObject = JSONObject(jsonError)
                showDialog.log(TAG, "sendMedicalTipsNotification error: $jsonObject")
            } catch (e: JSONException) {
                showDialog.log(TAG, "sendMedicalTipsNotification error: $e")
            }
        }
    }) {
        override fun getHeaders(): MutableMap<String, String> {
            return mutableMapOf("Authorization" to "Bearer ${Constants.MY_PROJECT_CLOUD_CONSOLE_CLIENT_ID}",
                    "Content-Type" to "application/json")
        }
    }

    Volley.newRequestQueue(ctx).add(request)
}

As you can see i'm sending my CLIENT_ID and Content Type in request header. I really don't know why i am getting this error

  • You need to send an access token to the service. You may test this using `export TOKEN=$(gcloud auth print-access-token)` and using the value of `TOKEN` as the Bearer value .... `"Bearer ${Constants.TOKEN}"`. – DazWilkin Dec 12 '20 at 18:27
  • Have a look at this: https://developers.google.com/api-client-library/java/google-api-java-client/oauth2 – DazWilkin Dec 12 '20 at 18:28

0 Answers0