【问题标题】:Authorization failed using Azure Service Bus API to manage queues使用 Azure 服务总线 API 管理队列的授权失败
【发布时间】:2021-02-24 08:47:35
【问题描述】:

我正在尝试使用 Azure 服务总线 api 从某些队列中清除消息。

根据文档 (https://docs.microsoft.com/en-us/rest/api/storageservices/clear-messages),我将使用以下请求来执行此操作:

https://myaccount.queue.core.windows.net/myqueue/messages

这看起来很简单,但问题是我无法让这个请求正确授权。 (结果 = 401 未经授权)

显然,签名过程相当复杂,并在此处进行了描述 (https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key)

我做了很多尝试,比如下面的代码:

                var httpClient = new HttpClient();
                using (HMACSHA256 hmac = new HMACSHA256())
                {
                    var StringToSign = $"GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:{DateTime.UtcNow.ToString("o")}\nx-ms-version:2015-02-21\n\n\n\n";
                    var stringToSignHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(StringToSign));
                    var base64StringToSign = Convert.ToBase64String(stringToSignHash);
                    
                    
                    var signature = $"{base64StringToSign}, {MySecretKey}";                        
                    using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Delete, "https://myaccount.servicebus.windows.net/myqueue/messages"))
                    {
                        //requestMessage.Headers.Add("x-ms-date", DateTime.UtcNow.ToString());
                        requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SharedKey", signature);
                        var result = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
                    }
                }

对于 MySecretKey,我使用了我的共享访问策略密钥。我尝试按原样使用,并将base64解码为ascii。

有人在这方面取得了更大的成功吗? 有没有更简单的方式访问api?

谢谢。

【问题讨论】:

    标签: azure azureservicebus azure-authentication


    【解决方案1】:

    您可以利用不同语言的代码here 来生成 SAS 令牌。

    更新: 您能否确认您正在尝试执行哪个 API?根据代码,您正在调用 myaccount.servicebus.windows.net 上的 Delete 方法(即服务总线资源)。 Delete API 操作完成对锁定消息的处理,并将其从队列或订阅中删除。您共享的示例/参考文章用于从存储队列中删除消息。如果您的要求是清除服务总线队列中的所有消息,那么您需要使用Recieve and Delete API。或者,您也可以使用service bus explorer 来清除消息。

    【讨论】:

    • 谢谢,这似乎更近了一步,但我仍然收到未经授权的错误。这次我可以看到它还返回“MalformedToken: Failed to parse simple web token”。
    • 您好,等我有空再回过头来。
    猜你喜欢
    • 2020-09-20
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2017-11-01
    • 2022-08-17
    相关资源
    最近更新 更多