我正在尝试为我的API管理生成访问令牌。我已经在Azure门户中启用了Management REST API,然后尝试通过门户以及以编程方式使用这两个选项生成令牌。这两个选项都不起作用,我得到了错误响应:
“ {\”错误\“:{\”代码\“:\” InvalidAuthenticationToken \“,\”消息\“:\” 访问令牌无效。\“}}”
我尝试访问的REST API:https://management.azure.com/subscriptions/{subscriptionID}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports//byApi?%24filter=timestamp%20ge%20datetime%272019-08-01T00%3A00%3A00%27%20and%20timestamp%20le%20datetime%272019-08-09T00%3A00%3A00%27&api-version=2019-01-01
我的代码:
public string GetAnalytics()
{
string data = String.Empty;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_url);
string token = GetToken();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
data = client.GetAsync(_url).Result.Content.ReadAsStringAsync().Result;
}
return data;
}
private string GetToken()
{
var id = "integration";
var key = _key;
var expiry = DateTime.UtcNow.AddDays(10);
string token = String.Empty;
using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
{
var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
var signature = Convert.ToBase64String(hash);
token = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);
}
return token;
}
参考文献:
https://docs.microsoft.com/en-us/rest/api/apimanagement/2019-01-01/reports/listbyapi
对此有任何帮助吗?
答案 0 :(得分:0)
您使用的API是Azure API,而不是Azure APIM API。共享访问签名仅适用于Azure APIM API,不适用于Azure API。为了使共享访问签名能够正常工作,请使用具有基本URL的API-https://{servicename}.management.azure-api.net
要使用Azure API,请使用OAuth2凭据。如上所述设置客户端-https://docs.microsoft.com/en-us/rest/api/azure/#register-your-client-application-with-azure-ad
答案 1 :(得分:0)
您使用的URL是azure rest api端点。如果要调用天蓝色的REST API,则需要获取天蓝色的广告访问令牌。但是,您获得的令牌是SAS令牌。它仅可用于调用Azure API管理Rest API。有关更多详细信息,请参阅 https://docs.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/api-management-rest