繁体   English   中英

如何使用共享访问策略连接字符串在 azure 服务总线中创建 SAS 策略

[英]How to create SAS policy in azure service bus using shared access policy connectionstring

我正在尝试使用 .NET Core 2.1 中的共享访问策略连接字符串为 azure 服务总线命名空间创建 SAS 策略。

我可以使用 Microsoft.Azure.Management.ServiceBus NuGet package 创建它,如下所示

private static async Task<string> GetToken()
    {
        try
        {
            // Check to see if the token has expired before requesting one.
            // We will go ahead and request a new one if we are within 2 minutes of the token expiring.
            if (tokenExpiresAtUtc < DateTime.UtcNow.AddMinutes(-2))
            {
                Console.WriteLine("Renewing token...");

                var tenantId = appOptions.TenantId;
                var clientId = appOptions.ClientId;
                var clientSecret = appOptions.ClientSecret;

                var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");

                var result = await context.AcquireTokenAsync(
                    "https://management.core.windows.net/",
                    new ClientCredential(clientId, clientSecret)
                );

                // If the token isn't a valid string, throw an error.
                if (string.IsNullOrEmpty(result.AccessToken))
                {
                    throw new Exception("Token result is empty!");
                }

                tokenExpiresAtUtc = result.ExpiresOn.UtcDateTime;
                tokenValue = result.AccessToken;
                Console.WriteLine("Token renewed successfully.");
            }

            return tokenValue;
        }
        catch (Exception e)
        {
            Console.WriteLine("Could not get a new token...");
            Console.WriteLine(e.Message);
            throw e;
        }
    }
private static async Task CreateSASPolicy()
    {
        try
        {
            if (string.IsNullOrEmpty(namespaceName))
            {
                throw new Exception("Namespace name is empty!");
            }

            var token = await GetToken();

            var creds = new TokenCredentials(token);
            var sbClient = new ServiceBusManagementClient(creds)
            {
                SubscriptionId = appOptions.SubscriptionId,
            };

            List<AccessRights?> list = new List<AccessRights?> { AccessRights.Send };
            var AuthRule = new SBAuthorizationRule { Rights = list };
            var authorizationRuleName = "SendRule"; //policy name
              
            Console.WriteLine("Creating SAS policy...");
            var result = sbClient.Namespaces.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, AuthRule).Result;
            Console.WriteLine("Created SAS policy successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Could not create a SAS policy...");
            Console.WriteLine(e.Message);
            throw e;
        }
    }

但是对于上面的代码,我需要至少为我们用来创建令牌的应用程序提供“Azure 服务总线数据所有者”。

我也试过使用 http 客户端如下

using (HttpClient httpclient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
        {
            httpclient.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", "", accessToken))));

            string baseAddress = @"https://management.core.windows.net/<subscriptionId>/services/ServiceBus/namespaces/<namespace>/AuthorizationRules/";

            var sendRule = new SharedAccessAuthorizationRule("contosoSendAll",
                new[] { AccessRights.Send });
            
            var result = await httpclient.GetAsync(baseAddress).ConfigureAwait(false);
            if (result.IsSuccessStatusCode)
            {
                var response = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
              
            }
        }

它返回 403(禁止访问)。

题:-

  • 有什么方法可以创建 SAS 策略而不授予应用程序“Azure 服务总线数据所有者”权限? 如何?
  • 可以使用共享访问策略连接字符串创建 SAS 策略吗? 如何?
  • 可以使用当前登录用户凭据创建 SAS 策略吗? 如何?

可以使用共享访问策略连接字符串创建 SAS 策略吗? 如何?

如果您使用共享访问策略连接字符串来创建 SAS 策略,我们就可以为主题或订阅创建策略。 对于命名空间,我们需要使用 Azure 资源提供者 API 来实现它。它是您当前使用的方式。 有关详细信息,请参阅 此处

关于如何为主题或队列创建策略,我们可以使用 package Azure.Messaging.ServiceBus.Administration

例如

ServiceBusAdministrationClient client = new ServiceBusAdministrationClient(connectionString);
   
            QueueProperties queue =await client.GetQueueAsync("myqueue");
            queue.AuthorizationRules.Add( new SharedAccessAuthorizationRule(
                 "manage",
                 new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })
            );
            queue= await client.UpdateQueueAsync(queue);

            foreach (var rule in queue.AuthorizationRules) {
                Console.WriteLine(rule.KeyName);
            }

在此处输入图像描述

有什么方法可以创建 SAS 策略而不授予应用程序“Azure 服务总线数据所有者”权限? 如何?

当我们使用 Azure Resource Provider API 创建资源时,我们应该拥有正确的 Azure RABC 权限。 关于创建策略,我们需要有权限Microsoft.ServiceBus/namespaces/authorizationRules/actionMicrosoft.ServiceBus/namespaces/authorizationRules/write 如果您不想使用Azure Service Bus Data Owner ,您可以创建具有这些权限的自定义角色。 有关详细信息,请参阅此处此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM