I ended up using following override of ServiceBusConnectionStringBuilder
that uses a SharedAccess Signature:
public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessSignature);
Based on this, here's the code I wrote. This first generates a SAS token using RootManagedAccessKey
that is valid for an hour and then uses that token to send a message to a queue.
using System;
using System.Text;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;
namespace SO60273377
{
class Program
{
static void Main(string[] args)
{
var endpoint = "sb://<namespace>.servicebus.windows.net/";
var queueName = "test";
var keyName = "RootManageSharedAccessKey";
var keyValue = "<key>";
var validityDuration = TimeSpan.FromHours(1);
TokenScope tokenScope = TokenScope.Entity;
var provider = (SharedAccessSignatureTokenProvider) TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue, validityDuration, tokenScope);
var token = provider.GetTokenAsync(endpoint+queueName, validityDuration).GetAwaiter().GetResult();
var sasToken = token.TokenValue;
Console.WriteLine("SAS Token: " + sasToken);
var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(endpoint, queueName, sasToken);
QueueClient client = new QueueClient(serviceBusConnectionStringBuilder, ReceiveMode.PeekLock);
client.SendAsync(new Message(Encoding.UTF8.GetBytes("This is a test"))).GetAwaiter().GetResult();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
}
Endpoint=sb://<namespacename>.servicebus.windows.net/;SharedAccessKeyName=<sas-policy-name>;SharedAccessKey=<sas-key>
. – Gaurav MantriSharedAccessSignature sig=<signature-string>&se=<expiry>&skn=<keyName>&sr=<URL-encoded-resourceURI>
– Amit