问题
I am using new Azure ServiceBus SDK which is .NET Standard 2.0 and I am finding it difficult to use SAS Token. Previously, it used to be MessagingFactory but in new SDK it's not there. ServiceBusConnectionStringBuilder has SAS Token but it also expects a connectionString.
Basically, I want to Send and Receive using SAS Policy (Send rule for Sending and Receive rule for Receiving) and SAS token created from connection string of these policies.
I am able to generate SAS Token but cannot find a way to create QueueClient using this token.
回答1:
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();
}
}
}
来源:https://stackoverflow.com/questions/60273377/using-sas-token-with-azure-servicebus