GCM http 401 authorization error

Pawel picture Pawel · Dec 11, 2013 · Viewed 77.3k times · Source

When my backend server sends post requests to GCM servers I get an authorization error HTTP 401.

I followed the steps described here:

http://developer.android.com/google/gcm/http.html#auth_error

>> api_key=AIzaSyDEy3...

>> curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_id\":\"ABC\"}"

I get this:

<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

In the troubleshooting it says:

Authentication Error
The sender account that you're trying to use to send a message couldn't be authenticated. Possible causes are:
    1. Authorization header missing or with invalid syntax.
    2. Invalid project number sent as key.
    3. Key valid but with GCM service disabled.
    4. Request originated from a server not whitelisted in the Server Key IPs.

I have questions about that:

  1. Is the header in the curl request correct?
  2. Do they mean "api_key" (AIzaSy…) or the Project number like 8305134….?
  3. How do I whitelist my Server Key IP?
  4. If I'm running the curl command, do I have to whitelist the IP-Address of my computer?

Answer

Vijay C picture Vijay C · Jan 30, 2014

Do they mean "api_key" (AIzaSy…) or the Project number like 8305134….?

It means Server key which should added in your curl script. The project number should not be used for sending message on server side.

To create the new server key, follow the steps,

  • Go to https://cloud.google.com/console/project
  • Click your Project
  • Go to APIs & auth on Left Panel
  • Select Credentials in submenu on Left Panel
  • Under Public API access, click on "Create New Key"
  • Choose 'Server'
  • On next dialog, Specify the whitelisted IPs, if you have any. Leaving it blank, the requests will be from any IP
  • Click Create.
  • You will find the new server key is created under "Public API Access"

This key is to be used for sending message in your script on server side.

How do I whitelist my Server Key IP?

You can whitelist while creating server key.

If I'm running the curl command, do I have to whitelist the IP-Address of my computer?

For testing purpose, you dont have to specify the IP. For commercial purpose, you may want to.

Warning setting IP to 0.0.0.0/0 as mentioned in the Getting Started guide will allow all IPv4 address, but not IPv6.