I need to access Microsoft Graph API using my API Scope and Audience.
I need to be able to acquire a token on behalf of a user in my API, using the token I received in my client mobile application. I have used MSAL package in Android and iOS to get the token from my client app registration in Azure.
I need to access multiple Graph resources.
Using Android and iOS native SDKs
Audience
Scope
Whenever I try to hit the API (https://graph.microsoft.com/v1.0/me) I get message stating Access token validation failure. Invalid audience.
The error usually occurs if you are trying to access Microsoft Graph with token generated with exposed API Scope and Audience.
Initially, I too got same error when I tried to call Microsoft Graph with token generated with custom API scope as below:
GET https://graph.microsoft.com/v1.0/me
To resolve the error, generate token using on-behalf of flow by passing above API token as assertion value.
In my case, I used below .NET code to acquire token using on-behalf flow and called Microsoft Graph API successfully like this:
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);
}
}
Response:
Reference:
.net - Azure AD AcquireTokenOnBehalfOf - Stack Overflow by me