我需要使用我的 API 范围和受众访问 Microsoft Graph API。
我需要能够使用我在客户端移动应用程序中收到的令牌,代表 API 中的用户获取令牌。我已在 Android 和 iOS 中使用 MSAL 包从 Azure 中的客户端应用程序注册中获取令牌。
我需要访问多个图形资源。
使用Android和iOS原生SDK
观众
范围
每当我尝试使用 API (https://graph.microsoft.com/v1.0/me) 时,我都会收到消息指出
Access token validation failure. Invalid audience.
如果您尝试使用通过公开的 API 范围和受众生成的令牌来访问 Microsoft Graph,通常会发生此错误。
最初,当我尝试使用自定义 API 范围生成的令牌调用 Microsoft Graph 时,我也遇到了相同的错误,如下所示:
GET https://graph.microsoft.com/v1.0/me
要解决该错误,请通过将上述 API 令牌作为断言值传递,使用“代表”流程生成令牌。 在我的例子中,我使用以下 .NET 代码使用代表流获取令牌,并成功调用 Microsoft Graph API,如下所示:
using Azure.Core;
using Azure.Identity;
class Program
{
static async Task Main(string[] args)
{
var scopes = new[] { "User.Read" };
var tenantId = "tenantId";
var clientId = "appId";
var clientSecret = "secret";
var apitoken = "token_with_api_scope";
var onBehalfOfCredential = new OnBehalfOfCredential(tenantId, clientId, clientSecret, apitoken);
var tokenRequestContext = new TokenRequestContext(scopes);
// Get the token
var token = await onBehalfOfCredential.GetTokenAsync(tokenRequestContext, new CancellationToken());
// Print the token to the console
Console.WriteLine($"Access Token: {token.Token}");
// Use HttpClient to call Graph API
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokenResult.Token);
var response = await httpClient.GetStringAsync("https://graph.microsoft.com/v1.0/me");
Console.WriteLine("\n API Response:");
Console.WriteLine(response);
}
}
参考:
.net - Azure AD AcquireTokenOnBehalfOf - Stack Overflow,作者: