A month or so ago, the Microsoft Graph .NET Client Library was released. Working with the Graph client has largely been direct web requests up until now, so the client library is a welcome addition. However, as I started to explore the library, I discovered that finding documentation was a bit challenging. This is a basic walkthrough of the client library to help people to get started with their first calls.
The Graph .NET Client Library is intended to be very extensible and work in a variety of situations. For this first introduction, we’ll just use Azure Active Directory and ADAL to authenticate ourselves into the graph. I’ve written about the AAD/ADAL process before, so instead of re-writing it now, you can follow the walkthrough here: Jonathan Huss – The Help Desk demo, Part 2 – Azure Active Directory. For the client library, we don’t need a certificate for authentication. We can just use a basic client id and client secret authentication model. The first part of this post describes how to generate the client id and client secret: Jonathan Huss – Getting started with the Azure Active Directory Graph Client Library. So, be sure that you’ve created your application with appropriate permissions in Azure and have the client id and client secret available.
Getting the bits
I’m just using a standard console app project for this demo. We need to download the Graph .NET Client Library bits from NuGet into our project. The NuGet package that we’re going to download is “Microsoft.Graph”:
We’ll also need to install “Microsoft.IdentityModel.Clients.ActiveDirectory”. This is commonly known as ADAL or the Active Directory Authentication Library:
The first thing that we’ll do is to create a GraphServiceClient. To do so, we need to tell the Graph Client Library how we want to authenticate. In this case, we’re using Azure as the authentication source and ADAL to handle the OAuth flow. The way that we tell the Graph Client Library to use Azure and ADAL is actually via the GraphServiceClient constructor itself, using the IAuthenticationProvider parameter:
As far as I know, there aren’t any pre-built AuthenticationProvider classes, so we’ll need to go create our own to work against Azure. This is actually sort of handy, since we could build whatever we needed if we were using some other kind of authentication, although some pre-built providers for known authentication sources would be convenient.
The first thing we need to do is to create our own AzureAuthenticationProvider class that implements the IAuthenticationProvider interface. When we do that, we discover that there is only one function, AuthenticateRequestAsync:
What in the world should we do in that function? Well, if you’ve ever worked against Azure/O365 services before (or any OAuth service, really), you likely know that to authenticate to the service, you need to send an Authorization header that includes the Bearer token (commonly known as the access token). That’s precisely what we’re going to do in this function. We’re going to provide authentication details to the request. The idea is that when the library sends the request, it passes through this function and provides us an opportunity to inject our Bearer token into that request.
Before we can pass the access token as part of the request, we need to acquire the access token. We’ll do that just like we always have in the past. You can find a walkthough toward the end of this post: Jonathan Huss – Getting Started with Azure Active Directory Graph Client Library. Our finished code looks like this:
class AzureAuthenticationProvider : IAuthenticationProvider
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
string clientId = "ae798feb-2a57-4738-8037-2e7d57ac6930";
string clientSecret = "84fxdktLxiXvax0iI/m1ARB+QaEpd2c8jZD6tQK9Alc=";
AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/jonhussdev.onmicrosoft.com/oauth2/token");
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
This function reaches out to the login.windows.net authority, passes our client id and client secret along with our resource identifier, and requests our token. Once the token has been received, it’s injected into the Authorization header with the Bearer prefix. For the sake of making this fairly clear and concise, there’s no storage or refreshing of the token, nor are there any Settings, ConfigurationManager, or token cache implementations. There’s also no error handling. Certainly in a production environment, you’d want to incorporate those components.
Now that we have our AzureAuthenticationProvider all built out, we just need to pass it to the GraphServiceClient via the constructor, like so:
GraphServiceClient client = new GraphServiceClient(new AzureAuthenticationProvider());
Piece of cake right? Yep.
Note: This is an app-only authentication model. The token acquisition steps are slightly different for a delegated authentication model, but can be found in numerous places on the Internet, such as https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx.
Retrieving some data
Now that we have our client all setup, let’s see if we can retrieve some data. There are quite a few properties on the client object that correspond to the Graph URL segments (documentation on URL segments here: http://graph.microsoft.io/en-us/docs).
Maybe we’d like to create a function to look up a user, something like this:
public async Task<User> GetUser(string userPrincipalName)
GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
User user = await graphClient.Users[userPrincipalName].Request().GetAsync();
If we run that with a breakpoint, we can see that, in fact, it does retrieve the requested user, which is sort of convenient that it works as anticipated.
What if we wanted to search for all of the users that have a last name that starts with some value, “Hu”, for example, which should provide us with all of the Husses, Hubbards, Huffmans, etc. Sure, we can do that using the Filter function (which results in an OData $filter parameter), like so:
When sending a query, the default maximum result size is 100 records. What if we want to return more than that by using the OData $top parameter? Yep, that works too (requesting 500 users, in this example):
Alternatively, we could use the .Top() function from the Request in place of the $top parameter:
Also, in the last two examples, we note that “NextPageRequest” is populated. This property tells us that there are more pages to be retrieved. If we want to retrieve all of the pages at once, we just need to iterate on that NextPageRequest property, like so:
The Graph Client Library has quite a few objects available for interaction. At least as of the current version of the Graph Client Library (v1.0.1 on 5/24/2016), the available objects are as follows. I certainly expect this to grow as the Graph itself grows.
There is quite a bit more that we can talk about regarding the Graph Client Library. I plan to write a follow up post that describes more of the functionality. Definitely comment and let me know what would be useful for you and I’ll try to include it. Hopefully, though, this is a good starting point to get folks past the “How in the world do I get started with the new Graph Client Library?!?” question.