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

Calling management.azure.com API fails due to authentication

我有一个通过 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 没有必要的范围。

我该如何解决?

您正在获取 MS Graph API 的访问令牌,而不是 Azure 管理 API。

使用以下范围:

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

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