The “Key” to Server Authentication for Google Cloud Messaging

Google cloud messaging (GCM) provides a framework for communication between an application server and client applications, including android mobile Apps. The three main components when implementing GCM for an android app are:

  • GCM connection servers
  • Application Server
  • Android App client

 

Google-provided Google Cloud Messaging (GCM) connection servers take messages from a custom Application Server and send these messages to a GCM-enabled Android App installed on a mobile device.

Authorizing communication from an application server to GCM connection servers requires a server API key. The first step is setting up GCM for an Android App is to create a “project” in the Google Developers Console and enable Google Cloud Messaging:

  1. Open the Google Developers Console
  2. Click Create Project.
  3. Supply a project name and click Create. Once the project has been created, a page appears that displays your project ID and project number.
  4. In the sidebar on the left, select APIs & auth.
  5. In the displayed list of APIs, turn the Google Cloud Messaging for Android toggle to ON.

Next, generate a server key.

  1. In the sidebar on the left, select APIs & auth > Credentials.
  2. Under Public API access, click Create new key.
  3. In the Create a new key dialog, click Server key.
  4. In the resulting configuration dialog, you may supply IP address to filter incoming messages by server IP in order to restrict access to only application server addresses. For testing purposes, you can leave this blank to allow any IP.

To note, there are several types of API keys – Server, Browser, Android and iOS – so make sure you choose “Server key.”  If you find you’re getting an authentication error (HTTP 401), check to make sure you’ve created the right type of key (I say this from experience, and several lost hours of troubleshooting).

This server API key will need to be used in your application server.  For example, in Google’s GCM server demo sample (link), you copy the API key into the api.key file, then build and deploy the demo web application.

To send a message to registered Android devices with the target App installed, the Application Server will issue a POST request to https://android.googleapis.com/gcm/send

A message request is made of 2 parts: HTTP header and HTTP body. For example:

Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{     
    "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
    "data" : {
          ...
    },
}

The value in the Authorization:key header must be the server API key. This serves to identify the authenticity of messages sent to GCM.

Leave a Reply

Your email address will not be published.

top