Authorization Failure when sending Notification

Asgar Ali 86 Reputation points
2023-03-17T14:01:50.7933333+00:00

I am trying to send Notification to a android device through Azure Notification Hub but i am getting Unauthorized(status code 401).Herre is the code for sending Notification.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Runtime.Remoting.Messaging;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Web;
using System.Security.Policy;
using System.Net.Mime;
using Microsoft.SqlServer.Server;

namespace TestSend
{
    internal class Program
    {
        static void Main(string[] args)
        {
            PostMessage().GetAwaiter().GetResult();
            Console.ReadLine();
        }
        static async Task PostMessage()
        {
            var client = new HttpClient();
            var se = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds + 300;
            var my_uri = HttpUtility.UrlEncode("https://irmtnh.servicebus.windows.net/IRMTNotificationHub").ToLower();
            var hash_string = $"my_uri\nse";
            var sha_signature = HttpUtility.UrlEncode(Convert.ToBase64String(EncryptString(hash_string)));
            var Param = HttpUtility.UrlEncode("api-version:2015-04");
            var auth = $"SharedAccessSignature sig={sha_signature}&se={se}&skn=DefaultFullSharedAccessSignature&sr={my_uri}";
            //client.DefaultRequestHeaders.Add("Content-Type", "application/json");
            client.DefaultRequestHeaders.Add("ServiceBusNotification-Format", "gcm");
            client.DefaultRequestHeaders.Add("Authorization", auth);
           
            // Set the body as appropriate
            var requestBody  = new
            {
                notification = new
                {
                    title = "Notification Hub Test Notification",
                    body = "This is a Test."
                },
                data = new
                {
                    property1 = "value1",
                    property2 = 42
                }
            };

            // Convert the message to JSON
            var jsonMessage = JsonConvert.SerializeObject(requestBody);
            
            var bodyContent = new StringContent(jsonMessage,Encoding.UTF8,"application/json");
          
            var url = "https://irmtnh.servicebus.windows.net";
           
           client.BaseAddress = new Uri(url);
          // var FullAddress = client.BaseAddress.ToString() ;
            var response = await client.PostAsync("/IRMTNotificationHub/messages/?api-version=2015-04", bodyContent);    
            Console.WriteLine(Convert.ToInt32(response.StatusCode));
           Console.WriteLine(response.Headers.ToString());
            Console.WriteLine(response.ReasonPhrase);
            Console.WriteLine(response.RequestMessage.ToString());
        }
       
        static byte[] EncryptString(string hash_string)
        {
            var key = Convert.FromBase64String("my key");
            var to_sign = Encoding.UTF8.GetBytes(hash_string);
            using (var hmac = new HMACSHA256(key))
            {
                return hmac.ComputeHash(to_sign);
            }
        }
    }
}
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.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Bryan Trach 17,842 Reputation points Microsoft Employee Moderator
2023-03-21T03:47:20.5533333+00:00

The error message "Unauthorized (status code 401)" indicates that the authorization failed. It seems that the issue is with the authorization header. You can try to check the following things:

Verify that the shared access signature (SAS) token is correct, correctly encoded, has not expired, is for the correct resource, has the correct permissions, is for the correct endpoint and API version and namespace. Also, verify that it's setup for the correct hub, entity, and policy.

Can you please check these items and let us know if these suggestions resolve the issue? If not, please let us know so we can assist you further.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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