Using SAS Token with Azure ServiceBus

我与影子孤独终老i 提交于 2021-02-11 16:56:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!