Authorize Send Requests

Requests sent to FCM from your app server or trusted environment must be authorized. The FCM HTTP v1 API uses a short-lived OAuth 2.0 access token generated for the service account associated with your Firebase project. The legacy protocols use long-lived API keys retrieved from the Firebase console. In both cases, you must add the required credential to each message request sent to FCM.

Authorize HTTP v1 send requests

Every Firebase project has a default service account. You can use this account to call Firebase server APIs from your app server or trusted environment. If you use a different service account, make sure it has Editor or Owner permissions.

To authenticate the service account and authorize it to access Firebase services, you must generate a private key file in JSON format and use this key to retrieve a short-lived OAuth 2.0 token. Once you have a valid token, you can add it in your server requests as required by the various Firebase services such as Remote Config or FCM.

To generate a private key file for your service account:

  1. In the Firebase console, open Settings > Service Accounts.
  2. Click Generate New Private Key, and confirm by clicking Generate Key.
  3. Securely store the JSON file containing the key. You'll need it to complete the next step.

To retrieve an access token:

To retrieve the token, you can use the Google API Client Library for your preferred language, referencing the private key JSON file as shown:

node.js

function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./service-account.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      SCOPES,
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

Python

def _get_access_token():
  """Retrieve a valid access token that can be used to authorize requests.

  :return: Access token.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      'service-account.json', FCM_SCOPE)
  access_token_info = credentials.get_access_token()
  return access_token_info.access_token

Java

private static String getAccessToken() throws IOException {
  GoogleCredential googleCredential = GoogleCredential
      .fromStream(new FileInputStream("service-account.json"))
      .createScoped(Arrays.asList(SCOPES));
  googleCredential.refreshToken();
  return googleCredential.getAccessToken();
}

Note that the call to refresh the token is idempotent. After your token expires, the token refresh method is called automatically to retrieve an updated token.

To authorize access to FCM, request the scope https://www.googleapis.com/auth/firebase.messaging.

To add the access token to an HTTP request header:

Add the token as the value of the Authorization header in the format Authorization: Bearer <access_token>:

node.js

headers: {
  'Authorization': 'Bearer ' + accessToken
}

Python

headers = {
  'Authorization': 'Bearer ' + _get_access_token(),
  'Content-Type': 'application/json; UTF-8',
}

Java

URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
return httpURLConnection;

Authorize legacy protocol send requests

With the HTTP legacy protocol, each request must contain the server key from the Cloud Messaging tab of the Firebase console Settings pane. For XMPP, you must use the same server key to establish a connection.

Authorize HTTP requests

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 the Cloud Messaging tab of the Firebase console Settings pane. Android, iOS, and browser 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.

For example:

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}

See Build Send Requests for full detail on creating send requests. The Legacy HTTP Protocol Reference provides a list of all the parameters your message can contain.

Checking the validity of a server key

If you receive authentication errors when sending messages, check the validity of your Server key. For example, on Android, run the following command:

# api_key=YOUR_SERVER_KEY

# curl --header "Authorization: key=$api_key" \
       --header Content-Type:"application/json" \
       https://fcm.googleapis.com/fcm/send \
       -d "{\"registration_ids\":[\"ABC\"]}"

If you receive a 401 HTTP status code, your Server key is not valid.

Authorize an XMPP connection

With XMPP, you can maintain a persistent, asynchronous, bidirectional connection to FCM servers. The connection can be used to send and receive messages between your server and your users' FCM-connected devices.

You can use most XMPP libraries to manage a long-lived connection to FCM. XMPP endpoint runs at fcm-xmpp.googleapis.com:5235. When testing functionality with non-production users, you should instead connect to the pre-production server at fcm-xmpp.googleapis.com:5236 (note the different port).

Regular testing on pre-production (a smaller environment where the latest FCM builds run) is beneficial for isolating real users from test code. Test devices and test code connecting to fcm-xmpp.googleapis.com:5236 should use a different FCM sender ID to avoid any risks of sending test messages to production users or sending upstream messages from production traffic over test connections.

The connection has two important requirements:

  • You must initiate a Transport Layer Security (TLS) connection. Note that FCM doesn't currently support the STARTTLS extension.
  • FCM requires a SASL PLAIN authentication mechanism using <your_FCM_Sender_Id>@gcm.googleapis.com (FCM sender ID) and the Server key as the password. These values are available in the Cloud Messaging tab of the Firebase console Settings pane.

If at any point the connection fails, you should immediately reconnect. There is no need to back off after a disconnect that happens after authentication. For each sender ID, FCM allows 1000 connections in parallel.

The following snippets illustrate how to perform authentication and authorization for an XMPP connection to FCM.

XMPP server

The XMPP server requests a connection to FCM

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

FCM

FCM opens the connection and requests an auth mechanism, including the PLAIN method.

<stream:features>
  <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
    <mechanism>X-OAUTH2</mechanism>
    <mechanism>X-GOOGLE-TOKEN</mechanism>
    <mechanism>PLAIN</mechanism>
  </mechanisms>
</stream:features>

XMPP server

The XMPP server must respond using the PLAIN auth method, providing the server key from the Cloud Messaging tab of the Firebase console Settings pane.

<auth mechanism="PLAIN"
xmlns="urn:ietf:params:xml:ns:xmpp-sasl">MTI2MjAwMzQ3OTMzQHByb2plY3RzLmdjbS5hb
mFTeUIzcmNaTmtmbnFLZEZiOW1oekNCaVlwT1JEQTJKV1d0dw==</auth>

FCM

<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>

XMPP server

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

FCM

<stream:features>
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
  <session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
</stream:features>

XMPP server

<iq type="set">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"></bind>
</iq>

FCM

<iq type="result">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
    <jid>SENDER_ID@gcm.googleapis.com/RESOURCE</jid>
  </bind>
</iq>

Note: FCM does not use the bound resource while routing messages.

See Build Send Requests for full detail on creating send requests. The Legacy XMPP Protocol Reference provides a list of all the parameters your message can contain.

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.