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.