Ryan Taite
Ryan Taite

Reputation: 839

Can I use the Microsoft Graph SDK with Azure AD Easy Auth

I have a C# .NET MVC Web App on Azure that I've turned Easy Auth on for Azure AD accounts. I would like to be able to use the Microsoft Graph SDK alongside it.

In the Easy Auth article written by cgillum linked above, he says:

I’ll also point out that I used HTTP primitives rather than using the official Graph API Client SDK. This was mainly to emphasize that access to the Azure AD Graph API can be written in any language and doesn’t require any SDKs (though you can certainly use the SDKs if you like).

I understand that this was written over a year ago and with AAD Graph in mind, but he said it was possible to use the AAD Graph SDK, so maybe it's possible for MS Graph. (I'd honestly be happy to see if either way, but there seems to be a big push to use MS Graph over AAD Graph)

Currently I'm able to make url calls to Microsoft Graph endpoint (https://graph.microsoft.com) in my controller like so:

public JObject GetMe()
{
    string accessToken = this.Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
    var url = "https://graph.microsoft.com/v1.0/me"; // MS Graph

    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var response = httpClient.GetStringAsync(url).Result;
        var json = JObject.Parse(response);
        return json;
    }
}

This returns:

{
   "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users/$entity",
   "id":"a4cxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
   "businessPhones":[
      "(xxx) xxx-xxxx"
   ],
   "displayName":"Ryan Taite",
   "givenName":"Ryan",
   "jobTitle":"xxxxxxxxxxxx",
   "mail":"[email protected]",
   "mobilePhone":"(xxx) xxx-xxxx",
   "officeLocation":"xxxxxxx",
   "preferredLanguage":"xxxxxxx",
   "surname":"Taite",
   "userPrincipalName":"[email protected]"
}

Am I restricted to constructing url calls?
Would it be possible to utilize the Microsoft.Graph SDK and Easy Auth so that I can make calls like below, where new AzureAuthenticationProvider() would utilize the Easy Auth accessToken somehow?:

public async Task<User> GetMeViaMsGraph()
{
    Microsoft.Graph.GraphServiceClient graphServiceClient = new Microsoft.Graph.GraphServiceClient(authenticationProvider:new AzureAuthenticationProvider());
    Microsoft.Graph.User user = await graphServiceClient.Me.Request().GetAsync();
    return user;
}

I found on the msgraph-sdk-dotnet GitHub an Overview section that discusses the AuthenticationProvider but I'm still not certain if what I'm asking is doable or not.


Update:

Following Nan Yu's example below I was able to get the desired results, but I just want to flesh it out here in case others want to see.

In my controller I have these functions:

// Get myself as a Microsoft.Graph User Object
public User GetMeViaMsGraph()
{
    string accessToken = this.Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProviderTest(accessToken)); // implementation not shown here, but it's the exact same as Nan Yu's
    User me = graphClient.Me.Request().GetAsync().Result;

    return me;
}

// Send the User object to my Index page
public ActionResult Index()
{
    return View(GetMeViaMsGraph());
}

I removed the async Task<User> and await because I was running into issues and needed to move on.

On my Index.cshtml page I have this to quickly show that I can access the User object and its data:

@using Microsoft.Graph;

@model User

<div>
    @Model.DisplayName
    @Model.GivenName
    @Model.SurName
    @Model.JobTitle
</div>

Upvotes: 1

Views: 1845

Answers (2)

Krishanu Majumder
Krishanu Majumder

Reputation: 41

After six years of the original question, and Nan Yu's answer, I stumbled upon this. With the newer version of graph SDK, the answer still works conceptually, but not syntactically. For what it's worth now, I am posting how I made it work as other may still find it helpful. My situation: I am using Easy-Auth or app-service authentication for my very old ASP.Net 4.8 Web forms application and I wanted to call graph API. My use-case is simple and hence I did not intend to use Microsoft.Web.Identity or MSAL.

The code I have used is as follows- Add a class like this:

public class AzureAuthenticationProviderGraphService : IAuthenticationProvider
{
    string accessToken = string.Empty;
    public AzureAuthenticationProviderGraphService(string accessToken)
    {
        this.accessToken = accessToken;

    }

    public async Task AuthenticateRequestAsync(RequestInformation request, 
        Dictionary<string, object> additionalAuthenticationContext = null, 
        CancellationToken cancellationToken = default)
    {
        Microsoft.Kiota.Abstractions.RequestHeaders headers =
            new Microsoft.Kiota.Abstractions.RequestHeaders();

        string token = string.Format("Bearer {0}", accessToken);
        headers.Add("Authorization", token);
        // Append the access token to the request.
        request.AddHeaders(
            headers
        );  
    }

}

Now create the graph service client like below:

                    GraphServiceClient graphClient =
                new GraphServiceClient(
                        new AzureAuthenticationProviderGraphService(accessToken)
                );

Upvotes: 1

Nan Yu
Nan Yu

Reputation: 27538

Not all API's features are supported by the SDKs , that is another reason we usually use HTTP primitives . But if you still want to use Easy Auth with Microsoft.Graph SDK , you add a class something like :

public class AzureAuthenticationProviderTest : IAuthenticationProvider
    {
        string accessToken = string.Empty;
        public AzureAuthenticationProviderTest(string accessToken) {
            this.accessToken = accessToken;

        }

        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            try
            {

                // Append the access token to the request.
                request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            }
            catch (Exception ex)
            {
            }
        }
    }

Pass your access token and used the sdk like :

 string accessToken = "YourAccessToken";
 GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProviderTest(accessToken));  
 var groupIDs = await graphClient.Users["UserUPN"].GetMemberGroups(false).Request().PostAsync();

Upvotes: 2

Related Questions