Azure Notification Hub + FCM v1 returns 201 Created, but notifications not received in Flutter Web app
I'm using Azure Notification Hub integrated with Firebase FCM v1 to send notifications to a Flutter Web app. I have successfully uploaded the Firebase service account details under the Notification Hub’s Firebase (FCM v1) configuration.
Steps followed:
Registered the FCM token from my Flutter Web app.
Sending notifications from a Python script using REST API.
Received 201 Created
response — no error returned.
Problem: Despite the 201 Created
response, the notification is not received in the Flutter Web app.
Here’s the code I’m using:.
def send_notification(fcm_token, title, body):
headers = {
"Authorization": sas_token,
"Content-Type": "application/json;charset=utf-8",
"ServiceBusNotification-Format": "gcm",
#"ServiceBusNotification-DeviceHandle": fcm_token, # or ServiceBusNotification-Tags: tag
#"x-ms-version": "2015-01"
}
# FCM v1 JSON Payload (fix format)
payload = {
"message": {
"token": fcm_token,
"notification": {
"title": "Test Notification",
"body": "This is a test message"
}
}
}
response = requests.post(url, json=payload, headers=headers)
print(response.status_code, response.text)
If I use "ServiceBusNotification-Format": "gcm"
, I get a 201 response but no notification is delivered. If I change it to "fcm"
, I get the following error: 400 Could not read notification body from the request
Questions:
What is the correct payload format for FCM v1 when using Azure Notification Hub?
Where can I find the latest documentation for sending notifications using Python with Azure Notification Hub and FCM v1?
Where can I view registered devices and notification delivery logs in the Azure portal?
Thank you!
Azure Notification Hubs
-
Laxman Reddy Revuri • 4,000 Reputation points • Microsoft External Staff
2025-04-14T19:38:59.3266667+00:00 Hi @Rondla Harish Reddy
Azure Notification Hubs (ANH) with FCM v1 requires specific configuration adjustments for successful notification delivery. you need to ensure that your payload is formatted correctly. The payload you provided seems to be aligned with FCM v1 requirements, but you should ensure that the ServiceBusNotification-Format header is set to "fcm" when sending notifications with FCM v1.payload = { "token": fcm_token, "notification": { "title": "Test Notification", "body": "This is a test message" } }
1.Enable diagnostic logs in Azure Portal → Notification Hub → Diagnostic settings
Stream to Azure Monitor/Event Hubs for analysis
Key metrics: outgoing.allpns.success and outgoing.allpns.invalidpayload
2.Use Azure Portal → Notification Hub → Registrations blade
Filter by FCM v1 platform type
references:
https://learn.microsoft.com/en-us/azure/notification-hubs/firebase-migration-rest#rest-api
https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-gcm-to-fcm#how-do-i-create-fcm-v1-template-registrations-with-sdks-or-rest-apis -
Laxman Reddy Revuri • 4,000 Reputation points • Microsoft External Staff
2025-04-16T17:03:05.0233333+00:00 Hi @Rondla Harish Reddy
We haven’t heard from you on the last response and was just checking back to see if you have a resolution yet. In case if you have any resolution please do share that same with the community as it can be helpful to others. Otherwise, will respond with more details and we will try to help. -
Laxman Reddy Revuri • 4,000 Reputation points • Microsoft External Staff
2025-04-17T17:57:39.4066667+00:00 Hi @Rondla Harish Reddy
We haven’t heard from you on the last response and was just checking back to see if you have a resolution yet. In case if you have any resolution please do share that same with the community as it can be helpful to others. Otherwise, will respond with more details and we will try to help. -
Rondla Harish Reddy • 0 Reputation points
2025-04-21T15:15:56.9866667+00:00 Hello @Laxman Reddy Revuri ,Thanks for the code response.
I am using below code based on your reply.import time import base64 import hmac import hashlib from urllib.parse import quote_plus import requests AZURE_NOTIFICATION_HUB_NAME = "hub name" AZURE_NAMESPACE = "azure hub namespace" AZURE_SAS_KEY_NAME = "Key name" AZURE_SAS_KEY_VALUE = "key here" def generate_sas_token(resource_uri, key_name, key_value, expiry_in_minutes=60): encoded_uri = quote_plus(resource_uri.lower()).lower() expiry = int(time.time()) + int(expiry_in_minutes) * 60 string_to_sign = f"{encoded_uri}\n{expiry}" decoded_key = base64.b64decode(key_value) signature = hmac.new(decoded_key, string_to_sign.encode('utf-8'), hashlib.sha256).digest() encoded_signature = quote_plus(base64.b64encode(signature)) token = f"SharedAccessSignature sr={encoded_uri}&sig={encoded_signature}&se={expiry}&skn={key_name}" return token def register_fcm_v1_device(fcm_token, tags=["myTag"]): resource_uri = f"https://{AZURE_NAMESPACE}.servicebus.windows.net/{AZURE_NOTIFICATION_HUB_NAME}/registrations" sas_token = generate_sas_token(resource_uri, AZURE_SAS_KEY_NAME, AZURE_SAS_KEY_VALUE) headers = { 'Content-Type': 'application/atom+xml;type=entry;charset=utf-8', 'Authorization': sas_token, 'x-ms-version': '2015-01' } body_template = """{ "notification": { "title": "$(title)", "body": "$(message)" } }""" xml_body = f"""<?xml version="1.0" encoding="utf-8"?> <entry xmlns="http://www.w3.org/2005/Atom"> <content type="application/xml"> <FcmV1TemplateRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"> <Tags>{','.join(tags)}</Tags> <FcmV1RegistrationId>{fcm_token}</FcmV1RegistrationId> <BodyTemplate><![CDATA[{body_template}]]></BodyTemplate> </FcmV1TemplateRegistrationDescription> </content> </entry>""" uri = f"https://{AZURE_NAMESPACE}.servicebus.windows.net/{AZURE_NOTIFICATION_HUB_NAME}/registrations/?api-version=2015-01" response = requests.post(uri, data=xml_body, headers=headers) return response.status_code, response.text def send_push_notification(tag, title, message): resource_uri = f"https://{AZURE_NAMESPACE}.servicebus.windows.net/{AZURE_NOTIFICATION_HUB_NAME}/messages" sas_token = generate_sas_token(resource_uri, AZURE_SAS_KEY_NAME, AZURE_SAS_KEY_VALUE) payload = { "title": title, "message": message } uri = f"{resource_uri}/?api-version=2020-06" headers = { 'Content-Type': 'application/json', 'ServiceBusNotification-Format': 'fcm', 'ServiceBusNotification-Tags': tag, 'Authorization': sas_token } response = requests.post(uri, json=payload, headers=headers) return response.status_code, response.text # Sample test run fcm_token = "fcm token" status, response = register_fcm_v1_device(fcm_token, tags=["315"]) print("Registration:", status, response) status, response = send_push_notification("315", "Hello FCMv1", "This is a test push via Azure") print("Notification Sent:", status, response)
But I am still getting the error:
Notification Sent: 401 Access Denied. Invalid SAS token.
Could you please suggest what I might be doing wrong? I have followed the provided links and used the correct credentials. Can you please confirm if the code is correct? -
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-22T06:51:04.47+00:00 Hello @ Rondla Harish Reddy , can you try below code and let me know
import time import base64 import hmac import hashlib from urllib.parse import quote_plus import requests # === CONFIGURATION === AZURE_NOTIFICATION_HUB_NAME = "your-hub-name" AZURE_NAMESPACE = "your-namespace" # without ".servicebus.windows.net" AZURE_SAS_KEY_NAME = "your-SAS-Key-Name" AZURE_SAS_KEY_VALUE = "your-SAS-Key-Value" FCM_TOKEN = "your-client-fcm-token" # === SAS TOKEN GENERATOR === def generate_sas_token(resource_uri, key_name, key_value, expiry_in_minutes=60): expiry = int(time.time()) + expiry_in_minutes * 60 string_to_sign = f"{quote_plus(resource_uri)}\n{expiry}" decoded_key = base64.b64decode(key_value) signature = hmac.new(decoded_key, string_to_sign.encode('utf-8'), hashlib.sha256).digest() encoded_signature = quote_plus(base64.b64encode(signature).decode()) return f"SharedAccessSignature sr={quote_plus(resource_uri)}&sig={encoded_signature}&se={expiry}&skn={key_name}" # === REGISTER FCM V1 DEVICE === def register_fcm_v1_device(fcm_token, tags=["defaultTag"]): resource_uri = f"https://{AZURE_NAMESPACE}.servicebus.windows.net/{AZURE_NOTIFICATION_HUB_NAME}" sas_token = generate_sas_token(resource_uri, AZURE_SAS_KEY_NAME, AZURE_SAS_KEY_VALUE) headers = { 'Content-Type': 'application/atom+xml;type=entry;charset=utf-8', 'Authorization': sas_token, 'x-ms-version': '2015-01' } body_template = """{ "message": { "notification": { "title": "$(title)", "body": "$(message)" } } }""" xml_body = f"""<?xml version="1.0" encoding="utf-8"?> <entry xmlns="http://www.w3.org/2005/Atom"> <content type="application/xml"> <FcmV1RegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"> <Tags>{','.join(tags)}</Tags> <FcmV1RegistrationId>{fcm_token}</FcmV1RegistrationId> <BodyTemplate><![CDATA[{body_template}]]></BodyTemplate> </FcmV1RegistrationDescription> </content> </entry>""" uri = f"{resource_uri}/registrations/?api-version=2015-01" response = requests.post(uri, headers=headers, data=xml_body) return response.status_code, response.text # === SEND NOTIFICATION === def send_push_notification(tag, title, message): resource_uri = f"https://{AZURE_NAMESPACE}.servicebus.windows.net/{AZURE_NOTIFICATION_HUB_NAME}" sas_token = generate_sas_token(resource_uri, AZURE_SAS_KEY_NAME, AZURE_SAS_KEY_VALUE) headers = { 'Content-Type': 'application/json;charset=utf-8', 'Authorization': sas_token, 'ServiceBusNotification-Format': 'template', 'ServiceBusNotification-Tags': tag } payload = { "title": title, "message": message } uri = f"{resource_uri}/messages/?api-version=2020-06" response = requests.post(uri, headers=headers, json=payload) return response.status_code, response.text # === TEST === if __name__ == "__main__": tag = "flutterUser" print("Registering device...") status, response = register_fcm_v1_device(FCM_TOKEN, tags=[tag]) print("Register status:", status) print(response) print("\nSending notification...") status, response = send_push_notification(tag, "Hello!", "This is a test FCM v1 push from Azure.") print("Notification status:", status) print(response)
-
Rondla Harish Reddy • 0 Reputation points
2025-04-22T11:56:58.9133333+00:00 Hi Sampath,I have tried with above code.
but still same error.
I gave SAS key name as "DefaultFullSharedAccessSignature"
and SAS key value as "tryhgfvbjknk,nmknknk,mknlkbkjmnkjbn"(this is not exact key but similar to this)
AZURE_NOTIFICATION_HUB_NAME = "your-hub-name"
AZURE_NAMESPACE = "your-namespace" # without ".servicebus.windows.net"
Hub name and Hub name space also provided properly but still same 401 issue.Registering device... Register status: 401 Access denied. Invalid SAS token. Sending notification... Notification status: 401 Access denied. Invalid SAS token.
-
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-22T12:02:54.4833333+00:00 can you check this Manage service account permissions this URL and can you try this
-
Rondla Harish Reddy • 0 Reputation points
2025-04-22T12:44:09.1033333+00:00 Checked it Sampath,
Integration service enabled already.
As we are observing access token is invalid, how to find which part of the token is invalid. -
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-23T16:55:35.88+00:00 Hello @Rondla Harish Reddy , I see most of the reference with android with FCM REST reference
are you look for same?
-
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-25T12:54:20.3+00:00 Hello @Rondla Harish Reddy , have you checked above comment .If you have any further queries, do let us know.
-
Rondla Harish Reddy • 0 Reputation points
2025-04-28T10:02:32.25+00:00 Hello Sampath,
I am able to register device and send data to FCM v1 but still I am not able to see any data in my FCM project. but I have successful logs in Notification Hub.How I can verify this. can you please guide.
-
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-29T07:38:50.0033333+00:00 Hello @Rondla Harish Reddy ,
Thanks for confirming that the device registration and notification send logic through Azure Notification Hub using FCM v1 is now working and returning successful responses. Since you're still not seeing notifications appear in your Flutter Web app, the issue now seems to be on the client side—specifically in how the browser is handling the incoming push messages.
For Flutter Web, Firebase Cloud Messaging relies on the browser’s Service Worker to receive and display push notifications. If the service worker is not properly configured or registered, the push message may be received by the browser but never shown to the user.
To resolve this, please make sure that you have a
firebase-messaging-sw.js
file in yourweb/
directory. This file should import and initialize Firebase using the same configuration as your app, and it should include the logic to handle background messages.importScripts('https://www.gstatic.com/firebasejs/9.6.10/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/9.6.10/firebase-messaging-compat.js'); firebase.initializeApp({ apiKey: "<YOUR-API-KEY>", authDomain: "<YOUR-AUTH-DOMAIN>", projectId: "<YOUR-PROJECT-ID>", storageBucket: "<YOUR-STORAGE-BUCKET>", messagingSenderId: "<YOUR-SENDER-ID>", appId: "<YOUR-APP-ID>" }); const messaging = firebase.messaging(); messaging.onBackgroundMessage(function(payload) { console.log('[firebase-messaging-sw.js] Received background message:', payload); const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, }; self.registration.showNotification(notificationTitle, notificationOptions); });
Also make sure that this service worker file is being registered in your
index.html
file.<script> if ('serviceWorker' in navigator) { navigator.serviceWorker.register('firebase-messaging-sw.js') .then(function(registration) { console.log("Service Worker Registered:", registration); }).catch(function(err) { console.error("Service Worker Registration Failed:", err); }); } </script>
Next, confirm that the Firebase token you are using in Azure Notification Hub was obtained correctly using the Web Push method. For web, Firebase requires that you generate the token using a VAPID key.
FirebaseMessaging messaging = FirebaseMessaging.instance; String? token = await messaging.getToken( vapidKey: "YOUR_PUBLIC_VAPID_KEY_FROM_FIREBASE" );
This token must match the one you used during registration in Azure Notification Hub.
At this point, since Azure Notification Hub is reporting successful logs, and your integration with FCM is confirmed, the most likely root cause is that the web client is either not handling the push messages or not displaying them properly. You can also verify message receipt by testing a direct send from Firebase Console using that same token. If that fails, it confirms the issue is on the client side.
For more details on Firebase Web messaging setup, you can refer to the official guide here: https://firebase.google.com/docs/cloud-messaging/js/receive
You may also revisit Azure Notification Hubs documentation for FCM v1 migration here: https://learn.microsoft.com/en-us/azure/notification-hubs/firebase-migration-rest
Let me know once you have confirmed the service worker setup and token registration. We can help further if needed based on what you see in browser developer tools or Firebase Console.
-
Rondla Harish Reddy • 0 Reputation points
2025-04-29T14:21:03.9866667+00:00 Hi Sampath,
I have created a proper function for generating the SAS token because the previous code you provided did not work. Please find the updated SAS token function below.import requests import urllib.parse import hmac import hashlib import base64 import datetime # Function to generate the SAS token def generate_sas_token(uri, key, policy_name, expiry=3600): expiry_time = int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds()) + expiry string_to_sign = f"{urllib.parse.quote(uri)}\n{expiry_time}" signature = base64.b64encode(hmac.new( key.encode('utf-8'), string_to_sign.encode('utf-8'), hashlib.sha256 ).digest()).decode('utf-8') sas_token = f"SharedAccessSignature sr={urllib.parse.quote(uri)}&sig={urllib.parse.quote(signature)}&se={expiry_time}&skn={policy_name}" return sas_token
We tested sending notifications directly from FCM using the token to our web app, and it worked—we successfully received the notifications. After that, we configured the same project credentials (private key, client email, and project ID) in the FCM v1 settings of the Notification Hub. We tried to identify the issue, but there were no failure responses or errors. In the Notification Hub metrics, everything shows successful registrations and a successful count of FCM v1 notifications.
I have followed your reference links, but the issue still persists. I'm unable to identify the exact cause of the problem. Could you please suggest any other ways I can troubleshoot or pinpoint where exactly the issue is? -
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-04-30T14:38:00.7233333+00:00 Hello @Rondla Harish Reddy ,
Thank you for the detailed follow-up and for confirming that direct FCM sends to your Flutter Web app are working correctly. That’s a great step forward and helps narrow down the issue significantly.
Based on your current setup and successful testing with Firebase directly, it appears the problem lies in how Azure Notification Hub interacts with Firebase Cloud Messaging for web platforms.
To clarify, while Azure Notification Hub supports FCM v1 for Android and iOS, it currently does not support Web Push tokens (which are generated in the browser using
vapidKey
). These Web Push tokens follow a different protocol and are not handled the same way by Notification Hub.Since the push is accepted by FCM but doesn’t reach your Flutter Web client, and NH logs show success, it strongly indicates this known gap in support for Web Push messaging through Azure Notification Hub.
Suggested next steps:
- For Flutter Web clients, I recommend sending notifications directly through Firebase Admin SDK or REST API, which you’ve already tested successfully.
- You can continue using Azure Notification Hub for your mobile (Android/iOS) notifications and handle web push separately in your backend by checking the platform type of the token.
Here’s the official documentation confirming current FCM v1 support scope: https://learn.microsoft.com/en-us/azure/notification-hubs/firebase-migration-rest
I understand this can be a bit of a blocker for web-based apps, and I encourage you to consider submitting feedback on the Azure Feedback Portal to raise visibility of this feature request for FCM Web token support.
-
Sampath • 2,345 Reputation points • Microsoft External Staff
2025-05-02T05:02:39.94+00:00 Hello @Rondla Harish Reddy ,
Have you checked the above comment? Do you have any other questions?
Sign in to comment