由于身份验证,调用management.azure.com API失败

时间:2019-09-30 18:18:08

标签: c# azure azure-active-directory asp.net-core-webapi azure-ad-graph-api

我有一个通过Azure活动目录工作的WEB API应用程序。

我可以像这样在活动目录中获取所有用户的信息:

var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(_applicationOptions).Build();
string[] scopes = { "https://graph.microsoft.com/.default" };

AuthenticationResult result = null;
try
{
    result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
}
catch (MsalServiceException ex)
{
    // Case when ex.Message contains:
    // AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default"
    // Mitigation: change the scope to be as expected
}

// use the default permissions assigned from within the Azure AD app registration portal
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/users");
string content = await response.Content.ReadAsStringAsync();

但是,如果我尝试让房客打电话

https://management.azure.com/tenants?api-version=2019-06-01

我收到AuthenticationFailed错误。

我猜这是因为我的AccessToken没有必要的范围。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您将获得MS Graph API的访问令牌,而不是Azure Management API。

使用以下范围:

https://management.core.windows.net/.default

文档: https://docs.microsoft.com/en-us/rest/api/azure/#authorization-code-grant-interactive-clients