Firebase FCM returns Unauthorized error with right server key - firebase

I am trying to send a push notification from my server using Firebase Cloud Messaging but keep getting the following error:
Client error: POST https://fcm.googleapis.com/v1/projects/my-project/messages:send resulted in a 401 Unauthorized response... Request had invalid authentication credentials. Expected OAuth 2 access
I have looked everywhere online and everywhere made mention of "using the Server Key instead of the API Key". I am doing this and still receiving the error. Nothing online has helped.
Here is my request:
POST https://fcm.googleapis.com/v1/projects/my-project/messages:send
Headers:
Authorization: Bearer <MY SERVER KEY>
Content-Type: application/x-www-form-urlencoded (I have also tried application/json)
Body:
{
"message": {
"topic": "",
"notifications": {
"title": "Some title",
"body": "Some notification body"
}
}
}
Push notifications directly from the Firebase console work just fine, I just can't get this to work server side.

It seems you are using the v1 HTTP API, but you're trying to authorize it using the instructions from the legacy API. They aren't compatible. As the documentation states:
Important: The server key found in the console cannot authorize send
requests made via the HTTP v1 API—it is used only for legacy HTTP and
XMPP requests.
If you want to use the v1 API, must follow the instructions in the v1 API documentation. If you don't want to use the v1 API, then you will have to use the legacy API instead.

Related

How to implement a Google Cloud Platform (GCP) Authorization call via HTTP call in postman

I want to implement an HTTP call to Google Cloud Platform (GCP) to generate the Authorization token.
Cant find a the correct GCP documentation for the same as well.
Using the reference from below URL, I was able to generate a Authorizaton token from Postman, using postmans Authorization UI and not the HTTP call UI.
https://www.vulongtran.com/how-to-use-postman-with-google-cloud-platform-apis
And the call to GCP API are working using the token generated from above process.
I tried implementing the same call via HTTP POST request, but not getting expected result.
HTTP POST
URL - https://accounts.google.com/o/oauth2/token
Query param-
grant_type:authorization_code
redirect_uri:https://www.getpostman.com/oauth2/callback
Authorization -
Basic Auth
username -
password -
Headers -
scope:https://www.googleapis.com/auth/cloud-platform
redirect_uri:https://www.google.com
And the response that I get is
400 bad request
{ "error": "invalid_request", "error_description": "Missing required parameter: code" }
2nd Try-
Also tried sending the in the request BODY, like below, but the result was same.
{
grant_type:'authorization_code',
redirect_uri:'https://www.getpostman.com/oauth2/callback'
}
Response
{
"error": "invalid_request",
"error_description": "Missing required parameter: code"
}
I saw another page, where 'code' is used in the call. Dont know what language the code on that page is for.
But I am unable to figure out the correct HTTP call to get the token from there as well.
Google OAuth2: Required parameter is missing: grant_type

Request blocked by CORS policy only when app is hosted in Firebase

My Flutter web app needs to call an API when the user submits a contact form. The API is that of a discord bot that proceeds to post the message in a specific channel on my Discord server. This setup works fine for two other apps that are using the same dependencies and the same production environment (Firebase hosting), but on this specific app it throws the following error:
Access to XMLHttpRequest at
'https://discordapp.com/api/channels/689799838509957177/messages' from
origin 'https://autonet.tk' has been blocked by CORS policy: Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
If I add the header 'Access-Control-Allow-Origin': '*' to the request, I just get a XMLHttpRequest error
My code:
import 'package:http/http.dart' as http;
var resp = await http.post(
"https://discordapp.com/api/channels/689799838509957177/messages",
headers: {
'Authorization': "Bot " + botToken,
},
body: {
"content": "NEW MESSAGE: " + body
});
Making it harder to triangulate the root cause is the fact that this runs fine on my local machine. It's only once I deploy the app to Firebase hosting that I get that CORS error.
Another thing worth noting is that on the Discord side, there is no configuration that I had to make in order to accept the incoming request for the other two web apps that work fine using the same code. (There is no list of allowed hosts).
'Access-Control-Allow-Origin' it's a header that must be in the response, not in the request. For more information, I suggest you this read:
https://stackoverflow.com/a/20035319/14106548
EDIT:
After a small research I think you are calling the wrong endpoint. This is why the response doesn't have the proper header attached.
The endpoint is:
https://discord.com/api
For more info look at: https://discord.com/developers/docs/reference

Google Dialogflow with API2 webhook: Failed to Parse response

I am trying to connect my bot to an azure function with a db. I entered the azure function URL as the webhook, it recieves the request as a POST http message.
I tried to respond with the following test message (and many more simpler ones):
{
"fulfillmentText":"fulfillmentText",
"fulfillmentMessages": [{"simpleResponse":{"textToSpeech":"text","ssml":"ssml","displayText":"text"}}]
}
and got a response:
Webhook call failed. Error: Failed to parse webhook JSON response:
Expect message object but got:
"笀∀昀甀氀昀椀氀氀洀攀渀琀吀攀砀琀∀㨀∀昀甀氀昀椀氀氀洀攀渀琀吀攀砀琀∀Ⰰ∀昀甀氀昀椀氀氀洀攀渀琀䴀攀猀猀愀最攀猀∀㨀嬀笀∀猀椀洀瀀氀攀刀攀猀瀀漀渀猀攀∀㨀笀∀琀攀砀琀吀漀匀瀀攀攀挀栀∀㨀∀琀攀砀琀∀Ⰰ∀猀猀洀氀∀㨀∀猀猀洀氀∀Ⰰ∀搀椀猀瀀氀愀礀吀攀砀琀∀㨀∀琀攀砀琀∀紀紀崀紀".
Everytime I enter a query in dialogflow I can check the diagnostic info and I see the response clearly in the "Fufillment Response" tab but then there's the above error in the "Response Status" tab.
Help would me much appreciated.
It looks like the content type of the HTTP response may be unclear. Make sure the HTTP response sets the content-type header explicitly to "application/json" or possibly event "application/json; charset=utf-8".
The problem has something to do with the Azure functions URL. For me a workaround was to write the function in visual studio, deploy to localhost, and use ngrok as a tunnel for dialogflow to call the webhook, rather than using the Azure Functions URL.

The request was missing an Authentication Key (FCM Token). Where to find that key? [duplicate]

I want to try to send a message using google's FCM messaging service and as the document says, the http request should be something like this:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
My problem is that I have not idea what Authorization's value should be and when I delete this header and make the request, I get error 401:Unauthorized.I think this must be some kind of api key or something but I cannot find it in my project. Can anyone help me?
PS: for testing purposes I currently am using this site to send a messsage to my device
According to About Firebase Cloud Messaging Server documentation:
Authentication
To send a message, the app server issues a POST request. For example:
https://fcm.googleapis.com/fcm/send
A message request consists of two parts: the HTTP header and the HTTP
body.
The HTTP header must contain the following headers:
Authorization: key=YOUR_SERVER_KEY
Make sure this is the server key, whose value is available in your Firebase project console under Project Settings > Cloud Messaging. Client keys or any other keys are rejected by FCM.
Content-Type: application/json for JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text.
If Content-Type is omitted, the format is assumed to be plain text.
UPDATE (2016/11/16)
Perhaps you should consider using the FCM token instead of the server keys as the note inside the following screenshot
UPDATE (2016/12/08)
Firebase has upgraded the server keys to a new version and recommended that you upgrade to the newest version. Please see the screenshot below:
i have also faced this error. The issue is with the server key. Don't use the api key from google-services.json file.
You should use the server api key from your firebase console project, at the cloud messaging tab project keys: https://console.firebase.google.com/project/firebase-probiz/settings/cloudmessaging
This is your Server key which you can observe into console.developers.google.com or Firebase project console under Project Settings > Cloud Messaging. Note the key it's auto created by Google Services. You ought add IP Address inco G.Console to restrict usage.
Plus do remember about Content-Type: application/json, otherwise you will get Error=MissingRegistration.

Apigee Console To Go Fails with 401 Apigee Platform Proxy Configured to use Oauth 2.0

We are using Apigee Platform to host our api's. Our Api Proxy in Apigee is configured to use Oauth 2.0 client_credentials and implicit grant types.
We are creating Console To Go to provide testing console for our API's to developers and Configured the console to use Oauth 2.0 Implicit Grant Flow.
When we test the actual calls, we always get 401 from Apigee. Here is the response
HTTP/1.1 401 API is secure. Needs security Credentials
WWW-Authenticate:
Bearer realm="null",error='invalid_token",error_description='oauth.v2.InvalidAccessToken: Invalid access token"
Content-Length:101
Content-Type:application/json
{
"fault": {
"faultstring": "Invalid access token",
"detail": {
"errorcode": "oauth.v2.InvalidAccessToken"
}
}
}
Actual Request that was sent to our API was:
GET /whodini/v1/discovery?email=puneet%40whodini.com HTTP/1.1
Authorization: OAuth M********N (Masked for security)
Host: whodiniinc-test.apigee.net
X-Target-URI: http://whodiniinc-test.apigee.net
Connection:
Keep-Alive
ValidateAccessToken policy of Apigee looks for token value in Authorization: Bearer {token} header and my suspicion is it fails with 401 because actual request made by Console to go contains Authorization: Oauth {token}.
Is there any way to
1. Control Authorization header value while using Oauth Implicit Grant Flow so that while making API calls Console to go uses Authorization: Bearer M********N instead of Authorization: OAuth M********N
Add a rule in the ValidateAccessToken policy of Apigee Proxy to that it interprets Authorization: OAuth M********N (Masked for security)
Please follow the below steps to resolve your issue:
Go to https://apigee.com/togo
Login
Select OAuth 2.0 Implicit Grant Flow (User Agent)
Select 'Draft Version' as '14 or later'
Click 'Save Credentials' button
Hope this helps. Please let me know if you have any further questions.
Thanks,
Archendra

Resources