14
votes

I'm getting many 401 Unauthorized errors when trying to connect to Google Cloud Message Server.

Our code was working for some time on our test server but on the production one it fails some times.

The API key was working ok, the push notifications arrive (eventually), but meanwhile I get a lot of 401 errors.

I've verified on the console that server IP address is on the white list:

When following Google Troublesooting guide, I get surprising results:

me@myserver:~$ :curl --header "Authorization: key=AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFFU" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
me@myserver:~$ curl --header "Authorization: key=AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFFU" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"
{"multicast_id":7560936933053964665,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
me@myserver:~$ curl --header "Authorization: key=AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFFU" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

Sometimes, the same curl command works and sometimes it doesn't without any change nor in the console nor in the command line... As sometimes it works, I asume the key it's ok (I've double checked the key and the allowed IPs several times).

I have checked all the stackoverflow questions and tested all the suggestions, but even removing all the IPs from the white list (to allow requests from any IP) the behavior is still the same, some times it works some times it doesn't

Some references I've checked:

Any advice on what can be going on would be very appreciated.

3

3 Answers

4
votes

After many checks and not finding a good result the only solution we could give was to create a new project (the 3rd one because we did it already before) with a new API key, and this 3rd time it works.

2
votes

I have solved my problem by creating new API Key under same project. Following this

Go to Google developer console then Select project Credentials -> Create Credentials -> API Key -> Server Key then add your server ip address where your GCM server code hosted.

After creating Api key it may takes 5 minutes to be workable

0
votes

It might happen that IPv6 is used for the connection while only IPv4 is allowed. Make sure you have 'Any IP allowed' not just IPv4 0.0.0.0/0.