0
votes

I am trying to implement Direct Batch send API to send notification. Using Postman to simulate the request. And it returns the Invalid authorization token error.

Post Request :

https://mynamespace.servicebus.windows.net/myHub/messages/$batch?direct&api-version=2015-08

With below Headers:

Content-Type:application/json Authorization:SharedAccessSignature sr=https://mynamespace.servicebus.windows.net/myHub/messages/$batch?direct%3fapi-version%3d2015-01&sig=xxxx&se=xxxx&skn=DefaultFullSharedAccessSignature

So how to resolved this error?

Also there is a APNS Example :

POST https://{Namespace}.servicebus.windows.net/{Notification Hub}/messages/$batch?direct&api-version=2015-08 HTTP/1.1
Content-Type: multipart/mixed; boundary="simple-boundary"
Authorization: SharedAccessSignature sr=https%3a%2f%2f{Namespace}.servicebus.windows.net%2f{Notification Hub}%2fmessages%2f%24batch%3fdirect%26api-version%3d2015-08&sig={Signature}&skn=DefaultFullSharedAccessSignature
ServiceBusNotification-Format: apple
Host: {Namespace}.servicebus.windows.net
Content-Length: 511
Expect: 100-continue
Connection: Keep-Alive


--simple-boundary
Content-Type: application/json
Content-Disposition: inline; name=notification

{"aps":{"alert":"Hello using APNS via Direct Batch Send!!!"}}
--simple-boundary
Content-Type: application/json
Content-Disposition: inline; name=devices

['Device Token1','Device Token2','Device Token3']
--simple-boundary--


--simple-boundary
Content-Type: application/json
Content-Disposition: inline; name=notification

{"aps":{"alert":"Hello using APNS via Direct Batch Send!!!"}}
--simple-boundary
Content-Type: application/json
Content-Disposition: inline; name=devices

['Device Token1','Device Token2','Device Token3']
--simple-boundary--

How to test it with Postman?

1

1 Answers

0
votes

Have you tried to call Direct Batch Send using NotificationHubs SDK? If yes can you compare the http request from SDK with what Postman is sending?

Also the documentation about filling out the Authorization header contains a few inaccuracies. Below C# code shows how to do it the right way.

string GenerateSasToken(Uri uri, string sasKeyName, string sasKeyValue)
{
    var targetUri = HttpUtility.UrlEncode(uri.ToString().ToLower(), Encoding.UTF8).ToLower();
    var expiresOnDate = Convert.ToInt64(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds) + 60*60 /* one hour */;
    var toSign = targetUri + "\n" + expiresOnDate;

    var keyBytes = Encoding.UTF8.GetBytes(sasKeyValue);
    var mac = new HMACSHA256(keyBytes);
    mac.Initialize();
    var rawHmac = mac.ComputeHash(Encoding.UTF8.GetBytes(toSign));
    var signature = HttpUtility.UrlEncode(Convert.ToBase64String(rawHmac), Encoding.UTF8);

    var token = "SharedAccessSignature sr=" + targetUri + "&sig=" + signature + "&se=" + expiresOnDate + "&skn=" + sasKeyName;
    return token;
}