Web push notifications with Azure Notification Hubs

Darli Varfi 5 Reputation points
2024-07-03T09:52:15.5533333+00:00

Hello Everyone,

I am new to Azure and i want more information from you about my problem.

Now what i want to do is set a web push (browser push) notification from Azure notification hub and i want to integrate it to my backend that is in .net core.

I have followed the instructions from here https://learn.microsoft.com/en-us/azure/notification-hubs/browser-push
and i am stuck here in this section https://learn.microsoft.com/en-us/azure/notification-hubs/browser-push#create-registrations-and-installations

Can you provide me an example of how this https://learn.microsoft.com/en-us/azure/notification-hubs/browser-push#create-browser-installations-sdk SDK works and how to implement it?

Thank you!

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
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,642 questions
0 comments No comments
{count} vote

3 answers

Sort by: Most helpful
  1. Ganeshkumar R 665 Reputation points
    2024-07-03T10:22:05.7066667+00:00

    Certainly! Setting up web push notifications using Azure Notification Hubs and integrating it with a .NET Core backend can be a bit complex, but I'll guide you through the process step by step.

    Prerequisites

    1. Azure Subscription: Ensure you have an Azure subscription.
    2. Notification Hub: Create a Notification Hub in your Azure portal.
    3. VAPID Keys: Generate VAPID keys for Web Push. You can use tools like web-push-codelab to generate these keys.

    Steps to Implement Web Push Notifications

    Step 1: Install Azure Notification Hubs SDK

    First, you need to install the Azure Notification Hubs SDK for .NET:

    
    dotnet add package Microsoft.Azure.NotificationHubs
    
    

    Step 2: Backend Setup

    Here's a simple example of how to set up your .NET Core backend to handle browser installations and send notifications.

    1. Create a Model for Registration

    Create a model to represent the registration details:

    
    public class Registration
    
    {
    
        public string Endpoint { get; set; }
    
        public string P256dh { get; set; }
    
        public string Auth { get; set; }
    
    }
    
    
    2. Create a Controller

    Create an API controller to handle registration and sending notifications:

    
    using Microsoft.AspNetCore.Mvc;
    
    using Microsoft.Azure.NotificationHubs;
    
    using System.Threading.Tasks;
    
    [ApiController]
    
    [Route("api/[controller]")]
    
    public class NotificationsController : ControllerBase
    
    {
    
        private readonly NotificationHubClient _hub;
    
        public NotificationsController()
    
        {
    
            string connectionString = "<Your_Notification_Hub_Connection_String>";
    
            string hubName = "<Your_Notification_Hub_Name>";
    
            _hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
    
        }
    
        [HttpPost("register")]
    
        public async Task<IActionResult> Register([FromBody] Registration registration)
    
        {
    
            var installation = new Installation
    
            {
    
                InstallationId = Guid.NewGuid().ToString(),
    
                Platform = NotificationPlatform.Web,
    
                PushChannel = registration.Endpoint,
    
                Tags = new List<string> { "browser" },
    
                Templates = new Dictionary<string, InstallationTemplate>
    
                {
    
                    ["genericMessage"] = new InstallationTemplate
    
                    {
    
                        Body = "{ \"notification\": { \"title\": \"$(title)\", \"body\": \"$(message)\" } }"
    
                    }
    
                }
    
            };
    
            installation.WebPushHeaders["p256dh"] = registration.P256dh;
    
            installation.WebPushHeaders["auth"] = registration.Auth;
    
            await _hub.CreateOrUpdateInstallationAsync(installation);
    
            return Ok();
    
        }
    
        [HttpPost("send")]
    
        public async Task<IActionResult> Send([FromBody] NotificationMessage message)
    
        {
    
            var notification = new Dictionary<string, string>
    
            {
    
                ["title"] = message.Title,
    
                ["message"] = message.Body
    
            };
    
            await _hub.SendTemplateNotificationAsync(notification, "browser");
    
            return Ok();
    
        }
    
    }
    
    public class NotificationMessage
    
    {
    
        public string Title { get; set; }
    
        public string Body { get; set; }
    
    }
    
    

    Step 3: Frontend Setup

    In your frontend, you need to handle the service worker registration and the subscription process.

    1. Service Worker

    Create a service worker file (sw.js):

    
    self.addEventListener('push', function(event) {
    
        var data = event.data.json();
    
        self.registration.showNotification(data.notification.title, {
    
            body: data.notification.body,
    
            icon: '/path/to/icon.png'
    
        });
    
    });
    
    
    2. Register Service Worker and Subscribe

    In your main JavaScript file:

    
    const vapidPublicKey = '<Your_VAPID_Public_Key>';
    
    navigator.serviceWorker.register('/sw.js')
    
        .then(function(registration) {
    
            return registration.pushManager.getSubscription()
    
                .then(async function(subscription) {
    
                    if (subscription) {
    
                        return subscription;
    
                    }
    
                    const response = await fetch('/api/notifications/publicKey');
    
                    const vapidPublicKey = await response.text();
    
                    const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
    
                    return registration.pushManager.subscribe({
    
                        userVisibleOnly: true,
    
                        applicationServerKey: convertedVapidKey
    
                    });
    
                });
    
        }).then(function(subscription) {
    
            fetch('/api/notifications/register', {
    
                method: 'POST',
    
                body: JSON.stringify({
    
                    endpoint: subscription.endpoint,
    
                    p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))),
    
                    auth: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth'))))
    
                }),
    
                headers: {
    
                    'Content-Type': 'application/json'
    
                }
    
            });
    
        });
    
    function urlBase64ToUint8Array(base64String) {
    
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
    
        const base64 = (base64String + padding)
    
            .replace(/-/g, '+')
    
            .replace(/_/g, '/');
    
        const rawData = window.atob(base64);
    
        const outputArray = new Uint8Array(rawData.length);
    
        for (let i = 0; i < rawData.length; ++i) {
    
            outputArray[i] = rawData.charCodeAt(i);
    
        }
    
        return outputArray;
    
    }
    
    

    Summary

    1. Backend:
      • Set up API endpoints for registration and sending notifications.
      • Use the Azure Notification Hubs SDK to handle installations and notifications.
    2. Frontend:
      • Register a service worker.
      • Subscribe to push notifications and send the subscription details to your backend.

    By following these steps and combining the backend and frontend code, you should be able to set up web push notifications using Azure Notification Hubs in a .NET Core application.

    If you have any specific questions or need further assistance, feel free to ask!


  2. MayankBakshi-0836 5 Reputation points
    2024-10-30T07:11:30.5266667+00:00

    I am also new and understand the above a little bit.
    I want to be able to send "Web Push Notification" to a PWA created from Power Pages site.
    Can I get detailed step-by-step instructions?

    0 comments No comments

  3. Damian Lascarez 0 Reputation points
    2024-11-14T03:07:08.2933333+00:00

    Hi everyone. If you have problems with the implementation. I have found a quick solution and it is working for me.

    First: Install this NuGet package, it is a copy of the official once, but with browser implemented:

    dotnet add package erikzhang.Microsoft.Azure.NotificationHubs
    

    To register your web browser, just need to use this code:

                try
                {
                    BrowserPushSubscription pushSubscription = new()
                    {
                        Endpoint = subscription.Endpoint,
                        P256DH = subscription.Keys.P256dh,
                        Auth = subscription.Keys.Auth
                    };
                    string registrationId = await _hub.CreateRegistrationIdAsync();
                    BrowserRegistrationDescription browserRegistration = new(pushSubscription)
                    {
                        RegistrationId = registrationId
                    };
                    await _hub.CreateOrUpdateRegistrationAsync(browserRegistration);
                }
                catch (Exception ex)
                {
                    return BadRequest(ex.Message);
                }
    

    Once you have your browser registered, you can use Azure Portal to test the Push:

    User's image

    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.