代码之家  ›  专栏  ›  技术社区  ›  ssk3

Azure EventHubs REST API 401未经授权

  •  0
  • ssk3  · 技术社区  · 6 年前

    我试图使用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 回复  |  直到 6 年前
        1
  •  1
  •   Shui shengbao    6 年前

    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"