Chris D
Chris D

Reputation: 134

App-Only Microsoft Graph authentication with Microsoft.Graph library

I am successfully retrieving an access token for the Microsoft Graph API with the App-Only flow, but the produced token can't seem to access anything.

Here is the authentication code I'm using:

var clientApp = new ConfidentialClientApplication(
    identifier,
    authority,
    "urn:ietf:wg:oauth:2.0:oob",
    new ClientCredential(secret), null, null);
var scopes = new string[] { $"{identifier}/.default" };
AuthenticationResult authResult = await clientApp.AcquireTokenForClientAsync(scopes);
return authResult.AccessToken;

From that, I do indeed get a token, but when I try to use it, it throws Access token validation failure. Here's the test query I've been using:

var users = service.Users.Request()
    .Filter($"mail eq '{resourceIdentifier}'")
    .Top(1)
    .GetAsync();
users.Wait();

For the API baseUrl, I was providing: https://graph.windows.net/{appId}. I did add api-version=1.6 to the query string (manually, as I don't see an option exposed through the Microsoft.Graph NuGet library). I had earlier tried https://graph.microsoft.com/v2.0, also to no avail.

Anyway, given the error messages about validation failure, I have come to believe that our (possibly tenant-specific?) API URI might be wrong. Could that be it? What am I not seeing?

Update

The solution had two components. The first was as mentioned in the accepted answer. The second was that the scope should be, simply, https://graph.microsoft.com/.default, despite my API calls being tenant-specific.

Upvotes: 2

Views: 1252

Answers (1)

Marc LaFleur
Marc LaFleur

Reputation: 33094

You're conflating two different APIs here.

The graph.windows.net URI is for the Azure AD Graph which is an entirely different API. For Microsoft Graph the URI should be graph.microsoft.com.

There is also isn't a /v2.0 of Microsoft Graph today. The publicly available versions are /v1.0 and /beta. Also note that when using the Microsoft Graph Client Library for .NET you shouldn't need to provide a baseUrl as it already defaults to https://graph.microsoft.com/v1.0.

Upvotes: 2

Related Questions