skip to Main Content

I am trying to set up and test push notifications using Firebase Cloud Messaging (FCM) with the new HTTP v1 API via Postman. I need to generate an OAuth 2.0 token to authenticate my requests and send a push notification to a specific device. I have the FCM service account JSON and the device token. Could someone guide me through the process of setting this up in Postman, including how to generate the OAuth 2.0 token and format the request?

Here are the details I have:

  • Service account JSON file from Firebase
  • Device token for the target device
  • Postman for executing HTTP requests

What are the steps to generate the OAuth 2.0 token using Python and set up the Postman request to send a push notification using FCM’s HTTP v1 API?

2

Answers


  1. Chosen as BEST ANSWER

    I believe this might be helpful to other developers. I will try to break down the steps as easily as possible.

    Step 1 - Download the Firebase Private Key

    Firebase Console => Project Setting => Service Accounts => Generate new private key

    enter image description here

    Step 2 - Generate OAuth 2.0 Token using FCM service account credentials. You can you thie Python to genrate it

      import json
      import jwt
      import time
      import requests  # This requires the `requests` library
    
      # Load the service account key JSON file
      with open('path_to_your_service_account.json', 'r') as f:
          service_account = json.load(f)
    
      # Define the JWT payload
      payload = {
          'iss': service_account['client_email'],
          'sub': service_account['client_email'],
          'aud': 'https://oauth2.googleapis.com/token',
          'iat': int(time.time()),
          'exp': int(time.time()) + 3600,
          'scope': 'https://www.googleapis.com/auth/firebase.messaging'
      }
    
      # Encode the JWT
      encoded_jwt = jwt.encode(payload, service_account['private_key'], algorithm='RS256')
    
      # Request an OAuth 2.0 token
      response = requests.post('https://oauth2.googleapis.com/token', data={
          'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
          'assertion': encoded_jwt
      })
    
      oauth2_token = response.json()['access_token']
      print(oauth_token)
    

    if you get this error

    Algorithm 'RS256' could not be found. Do you have cryptography installed

    make sure to run pip install cryptography this will install cryptography package to your machine.

    The print statment will have a format of ya29.ElqKBGN2Ri_Uz...HnS_uNreA this is the Oauth 2.0 token.

    Step 3 - Postman configration, plug in the token you have found insde the postman config

    enter image description here

    you can get your project id from the url of the firebase project

    Method: POST
    URL: https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send
    Headers:
    Content-Type: application/json
    Authorization: Bearer {oauth2_token}
    

    Notification body

      "message": {
        "token": "DEVICE_REGISTRATION_TOKEN",
        "notification": {
          "title": "Test Notification",
          "body": "This is a test message from Postman."
        }
      }
    }
    

  2. In your Flutter project create a new file and add this code:

    import 'dart:convert';
    import 'package:firebase_admin_sdk/firebase_admin_sdk.dart';
    import 'package:http/http.dart' as http;
    
    Future<String> getOAuthToken() async {
      final serviceAccount = ServiceAccount.fromJson(
        json.decode(await rootBundle.loadString('path/to/service-account.json')),
      );
      final credentials = GoogleCredentials.fromServiceAccount(serviceAccount);
      final accessToken = await credentials.tokenInfo.accessToken;
      return accessToken.toString();
    }
    

    Replace ‘path/to/service-account.json’ with the actual path to your Firebase service account JSON file.
    Call the getOAuthToken() function to get the OAuth 2.0 access token.
    Create a new request in Postman and set the request type to "POST".
    In the request URL, enter: https://fcm.googleapis.com/v1/projects/{YOUR_PROJECT_ID}/messages:send
    Replace {YOUR_PROJECT_ID} with your Firebase project ID, which you can find in the Firebase console.
    In the "Headers" tab, add the following key-value pairs:
    Content-Type: application/json
    Authorization: Bearer {YOUR_ACCESS_TOKEN}
    Replace {YOUR_ACCESS_TOKEN} with the access token you generated in the previous step.
    In the "Body" tab, select "raw" and "JSON" as the data type.Then enter the following JSON payload:

    {
      "message": {
        "token": "{DEVICE_TOKEN}",
        "notification": {
          "title": "Test Notification",
          "body": "This is a test push notification."
        }
      }
    }
    

    Replace {DEVICE_TOKEN} with the device token you have for the target device.
    Click the "Send" button in Postman to execute the request and send the push notification.
    You should see a response from the FCM API indicating whether the push notification was successfully delivered.
    Here’s the complete Flutter code to generate the OAuth 2.0 access token and send the push notification:

    import 'dart:convert';
    import 'package:firebase_admin_sdk/firebase_admin_sdk.dart';
    import 'package:http/http.dart' as http;
    
    Future<void> sendPushNotification() async {
      final accessToken = await getOAuthToken();
    
      final url = Uri.parse('https://fcm.googleapis.com/v1/projects/{YOUR_PROJECT_ID}/messages:send');
      final headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $accessToken',
      };
      final body = jsonEncode({
        'message': {
          'token': '{DEVICE_TOKEN}',
          'notification': {
            'title': 'Test Notification',
            'body': 'This is a test push notification.',
          },
        },
      });
    
      final response = await http.post(url, headers: headers, body: body);
      if (response.statusCode == 200) {
        print('Push notification sent successfully');
      } else {
        print('Failed to send push notification: ${response.statusCode} - ${response.body}');
      }
    }
    
    Future<String> getOAuthToken() async {
      final serviceAccount = ServiceAccount.fromJson(
        json.decode(await rootBundle.loadString('path/to/service-account.json')),
      );
      final credentials = GoogleCredentials.fromServiceAccount(serviceAccount);
      final accessToken = await credentials.tokenInfo.accessToken;
      return accessToken.toString();
    }
    

    Remember to replace the following placeholders:
    {YOUR_PROJECT_ID}: Your Firebase project ID
    {DEVICE_TOKEN}: The device token for the target device
    ‘path/to/service-account.json’: The actual path to your Firebase service account JSON file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search