用于访问图形令牌的 Azure AD 令牌

问题描述 投票:0回答:1

我需要使用我的 API 范围和受众访问 Microsoft Graph API。

我需要能够使用我在客户端移动应用程序中收到的令牌,代表 API 中的用户获取令牌。我已在 Android 和 iOS 中使用 MSAL 包从 Azure 中的客户端应用程序注册中获取令牌。

我需要访问多个图形资源。

使用Android和iOS原生SDK

Android SDK

iOS SDK

观众

Token Audience

范围

Token scope

每当我尝试使用 API (https://graph.microsoft.com/v1.0/me) 时,我都会收到消息指出

Access token validation failure. Invalid audience.

enter image description here

azure-active-directory single-sign-on azure-ad-msal
1个回答
0
投票

如果您尝试使用通过公开的 API 范围和受众生成的令牌来访问 Microsoft Graph,通常会发生此错误。

最初,当我尝试使用自定义 API 范围生成的令牌调用 Microsoft Graph 时,我也遇到了相同的错误,如下所示:

GET https://graph.microsoft.com/v1.0/me

enter image description here

要解决该错误,请通过将上述 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); } }

回复:

enter image description here

参考:

.net - Azure AD AcquireTokenOnBehalfOf - Stack Overflow,作者:

me

© www.soinside.com 2019 - 2024. All rights reserved.