Azure EventHubs REST API 401未经授权

时间:2018-03-02 06:54:18

标签: c# azure curl azure-eventhub azure-cli

我尝试使用curl执行eventhubs restapi,但它不起作用。

卷曲

curl --proxy $PROXY -i -X "GET" "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.EventHub/namespaces/$NAME_SPACE/eventhubs/$EVENTHUB?api-version=2017-04-01" -H "Authorization: $TOKEN"

生成SAS(C#)

var resourceuri = "https://myspacename.servicebus.windows.net/myeventhub";
            var key = "mykey";
            var keyname = "mykeyname";
            TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var week = 60 * 60 * 24 * 7;
            var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);

            string stringToSign = Uri.EscapeDataString(resourceuri) + "\n" + expiry;
            HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            var sasToken = String.Format("SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", Uri.EscapeDataString(resourceuri), Uri.EscapeDataString(signature), expiry, keyname);
            return sasToken;

响应

{"error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication failed. The 'Authorization' header is provided in an invalid format."}}

我引用了这个文档(https://docs.microsoft.com/ja-jp/rest/api/eventhub/Generate-SAS-token?redirectedfrom=MSDN)。 此外,我尝试使用此工具(https://github.com/sandrinodimattia/RedDog/releases/tag/0.2.0.1),但也是同样的结果。

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

API(https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.EventHub/namespaces/$NAME_SPACE/eventhubs/$EVENTHUB?api-version=2017-04-01)是Azure Rest API。您可以获得如下标记:

curl -X "POST" "https://login.microsoftonline.com/$TENANTID/oauth2/token" \
-H "Cookie: flight-uxoptin=true; stsservicecookie=ests; x-ms-gateway-slice=productionb; stsservicecookie=ests" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "client_id=$APPID" \
--data-urlencode "grant_type=client_credentials" \
--data-urlencode "client_secret=$PASSWORD" \
--data-urlencode "resource=https://management.azure.com/"

当您请求API时,在标题中,您应该使用-H "Authorization: Bearer $token"。所以,你应该修改如下:

curl --proxy $PROXY -i -X "GET" "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.EventHub/namespaces/$NAME_SPACE/eventhubs/$EVENTHUB?api-version=2017-04-01" -H "Authorization: Bearer $token"