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:
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?
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
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
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."
}
}
}