结合使用SAS令牌和Azure ServiceBus [英] Using SAS Token with Azure ServiceBus

查看:84
本文介绍了结合使用SAS令牌和Azure ServiceBus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的Azure ServiceBus SDK,它是.NET Standard 2.0,并且发现使用SAS令牌很困难.以前,它以前是MessagingFactory,但在新的SDK中不存在.ServiceBusConnectionStringBuilder具有SAS令牌,但也需要connectionString.

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.

基本上,我想使用SAS策略(用于发送和接收规则的发送规则)和从这些策略的连接字符串创建的SAS令牌进行发送和接收.

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.

我能够生成SAS令牌,但是找不到使用此令牌创建QueueClient的方法.

I am able to generate SAS Token but cannot find a way to create QueueClient using this token.

推荐答案

我最终使用了使用共享访问签名的ServiceBusConnectionStringBuilder :

I ended up using following override of ServiceBusConnectionStringBuilder that uses a SharedAccess Signature:

public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessSignature);

基于此,这是我编写的代码.这首先使用有效期为一个小时的 RootManagedAccessKey 生成SAS令牌,然后使用该令牌将消息发送到队列.

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();
        }
    }
}

这篇关于结合使用SAS令牌和Azure ServiceBus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆