0
votes

I am trying to write a .netcore API which gets a bearer token from third party Webapp. This .netcore API should access the Microsoft graph API and get the user group information back from Azure AD.

I was following the sample project https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore.

But unfortunately this uses AAD graph rather tha Microsoft graph API.

I tried to implement Graph API in the .netcore api project in the above sample.

Things I have tried

I have changed the AAD graph to Graph API in the AzureAdAuthenticationBuilderExtensions.cs(in the web app project)

options.Resource = "https://graph.microsoft.com";

Also I used the Microsoft.Graph nuget in the API project. And I am trying to create the GraphServiceClient using the code below

public GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
    {
        var words = accessToken.Split(' ');
        var token = words[1];
        var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

            return Task.FromResult(0);
        });

        var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? new HttpProvider());

        return graphClient;
    }

And finally I am trying to access the user information using the code below,

public async Task<IEnumerable<Group>> GetGroupAsync(string accessToken)
    {
        var graphClient = GetClient(accessToken);
        try
        {
            User me = await graphClient.Me.Request().GetAsync();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        var user= await graphClient.Users["***"].Request().Expand("MemberOf").GetAsync();


        var userEmail = "[email protected]";
        var usergroup = await graphClient.Users[userEmail].GetMemberGroups(false).Request().PostAsync();
        var groupList = new List<Group>();

        foreach (var g in usergroup.CurrentPage)
        {
            var groupObject = await graphClient.Groups[g].Request().GetAsync();
            groupList.Add(groupObject);
        }
        return groupList;
    }

But when I try the code I am getting the error "Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken Message: Access token validation failure.Inner error at Microsoft.Graph.HttpProvider."

Can somebody help me please?

Thanks in advance

1
I'm facing the same issue - How did you resolve it? I'd be thankful if you could share the code - MatterOfFact

1 Answers

0
votes

The access token passed to GetGroupAsync is not correct , and i am confused why you need to split the token :

var words = accessToken.Split(' ');
var token = words[1];

But never mind , since you have modified options.Resource = "https://graph.microsoft.com"; ADAL will help you get access token for Microsoft Graph API in OnAuthorizationCodeReceived function , and save the tokens to cache .

To get the access token , you could use ADAL to get the token from cache :

AuthenticationResult result = null;
// Because we signed-in already in the WebApp, the userObjectId is know
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;

// Using ADAL.Net, get a bearer token to access the TodoListService
AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

Then you could pass that token to your function:

await GetGroupAsync(result.AccessToken);

Modify your GetClient function to delete the split part:

public GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
{

    var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

        return Task.FromResult(0);
    });

    var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? new HttpProvider());

    return graphClient;
}