Authorization failure while registering a web subscription to Azure notification hub, Node JS

Kule, Rohit 0 Reputation points
2024-10-01T13:46:54.2433333+00:00

I have been trying to use the Browser(Web Push) for push notifications in browsers. The service worker and the subscription is successful, however while sending this subscription for registration on Azure notification hub, the register api fails with Invalid SAS Token.

Below is my token generation code:

function createSharedAccessToken(uri, saName, saKey) { 
    if (!uri || !saName || !saKey) { 
            throw "Missing required parameter"; 
        } 
    var encoded = encodeURIComponent(uri); 
    var now = new Date(); 
    var week = 60*60*24*7;
    var ttl = Math.round(now.getTime() / 1000) + week;
    var signature = encoded + '\n' + ttl; 
    var hash = crypto.createHmac('sha256', saKey).update(signature, 'utf8').digest('base64'); 
    return 'SharedAccessSignature sr=' + encoded + '&sig=' + encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName; 
  }

async function registerBrowserWithNotificationHub(hubName, namespace, sasToken, webPushSubscription) {
    const resourceUri = `https://${namespace}.servicebus.windows.net/${hubName}/registrations/?api-version=2015-01`;

    const registrationPayload = {
        "registrationId": webPushSubscription.endpoint,  // Browser endpoint
        "platform": "web",
        "pnsHandle": webPushSubscription.endpoint,
        "tags": ["browser"],
        "webPushAuth": webPushSubscription.keys.auth,
        "webPushP256dh": webPushSubscription.keys.p256dh
    };

    try {
        const response = await axios.post(resourceUri, registrationPayload, {
            headers: {
                'Authorization': sasToken,  // SAS token here
                'Content-Type': 'application/json',
            },
        });
        console.log('Registration successful:', response.data);
    } catch (error) {
        console.error('Error registering with Notification Hub:', error.response ? error.response.data : error.message);
    }
}


// Endpoint to register browser push subscription
app.post('/register', async (req, res) => {
    const subscription = req.body;

    // Generate SAS token
    const url = 'https://testpushnotificationnamespace.servicebus.windows.net/pushnotification';
    const sasToken = createSharedAccessToken(url.toLowerCase(),sasKeyName, sasKey)
      
    // Register the browser with Azure Notification Hub
    await registerBrowserWithNotificationHub('PushNotification', 'TestPushNotificationNamespace', sasToken, subscription);
});


I had checked the SAS Token generation code from the documentation, also rechecked that while generating the token the url encoding is done for the resourceURL.

Also, is there any other way to implement the Web Push of Azure Notifications in Node JS. Previously had referred the "azure-sb" npm package, however the web push feature is still not updated there.

Azure Notification Hubs
Azure Notification Hubs
An Azure service that is used to send push notifications to all major platforms from the cloud or on-premises environments.
326 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Hima Bindu 160 Reputation points
    2024-10-09T01:38:54.2333333+00:00

    Hi @Kule, Rohit
    Welcome to the Microsoft Q&A Platform!
    Try these steps:

    Use REST API Directly: Interact with the Azure Notification Hub REST API for full control over your requests.
    https://learn.microsoft.com/en-us/azure/notification-hubs/

    Check Notification Hub-Specific Documentation: Make sure you're using token generation instructions specific to Azure Notification Hub, not Event Hubs. Review Azure Notification Hubs Documentation.
    https://learn.microsoft.com/en-us/azure/notification-hubs/

    Check Permissions: Ensure your Shared Access Policy has Listen, Send, and Manage permissions. See Azure Notification Hubs Security.

    API Version: Try using a newer API version, as older ones may not fully support Web Push. Azure Notification Hubs API Versions.
    https://learn.microsoft.com/en-us/rest/api/notificationhubs/

    Consider FCM: If the problem persists, look into integrating with Firebase Cloud Messaging (FCM) for Web Push notifications.

    Debugging: Log the full URL, headers, body, and SAS token to find any issues.
    If the answer is helpful, please click "Accept Answer" and kindly upvote it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.