Before you begin with Microsoft Graph API

Fiqri Ismail
Aug 18, 2018 · 12 min read

If you are wondering what Microsoft Graph is? In simple words it is an API for Office 365. This API allows you to connect securely to Office 365, Windows 10 and Enterprise Mobility. Although it says an API to Office 365 you can do so many things using it.

What you can do with Microsoft Graph?

At this moment if I categorise these things in to a top level you can:

  1. On board People.
  2. Integrate/Work with Excel.
  3. Manage your calendars meeting across multiple users.
  4. Convert Documents to PDFs

On boarding people made easy using Microsoft Graph API. Also let you automate the work flow process.

Automating on boarding work flow (Image Source: Microsoft)

As you see above these operations can be automated using Graph API. When a new hire to a company creating a profile, assigning license or giving them roles. This will save a load of time in an organization. As well as same can be used to mange users.

Excel integration is another awesome part of the Graph API. This let you to access Excel workbooks stored in OneDrive and use power of Excel functions in your applications. As an example you can insert data of a survey and process it in Excel and then get the results to another applications using Graph API to Excel REST APIs.

A workflow to get data from Excel using Graph API (Image Source: Microsoft)

Above work flow gives you an idea of how this work flow works. You locate the workbook in OneDrive and then find the worksheet, finally get the data from worksheet to your application. As you see using Graph API you can access your OneDrive storage too.

What, if you need to access your meeting and calendars in Outlook. Yep Graph API supports that work flow too. If you need to manage these data you can easily use Graph API to access these information. Also you can read mails and moderate them too. Below is an example work flow of managing meeting in Outlook.

Finding meeting times using Graph API (Image Source: Microsoft)

Another great feature Graph API provide is that convert your documents from multiple formats to PDFs. This is a very good and needed feature for organisation to manage their documents in one format. Or to distribute across their users. Cause PDF is a standard format all can read and understand it without any complications.

Converting different formats of documents to PDF (Image Source: Microsoft)

OK, Now we know few things that can be achieved using Graph API. Next step is to check what you need to access Graph API or how to do that. First things first. Microsoft has given us a small playground to play around with Graph API. Its called Graph Explorer.

Graph Explorer allows you to try out supported API calls using Graph API and play around with it and understand the usage of it. Lets have a look on Graph Explorer.

Go to this URL (or click on it) : https://goo.gl/o8eeBe

Graph Explorer

As you see in the left side of the explorer there is a Sign in with Microsoft button. It means to access Graph API you need to authenticate first using a Microsoft Account. At the moment you can use any account associated with Microsoft Live account.

Then after only you will be able to access the Graph API. Lets try login in to our live account and click on one of the samples provided in the left side.

This is how it looks like after Authentication

As you see after authentication you will able to modify the permission how or sign out. Now in the Sample Queries section in the left side pane. Click one the queries and see how it works.

Sample Queries in Graph Explorer

I just clicked on the first one to grab “my profile”.

You should see the successful response bottom right side of the screen in JSON format.

Response from Graph API

If you look at the top part of the screen in the right side pane:

Graph API end point.

You see the end point. Where it hits to get the data. And you see the and point uses GET method to reach the end point. This gives you an idea of how to use the Graph API end points inside your application. So main two things are required to get the data you need from Graph API.

  1. Authenticate using a Microsoft Account
  2. Then reach the end point of Graph API

Lets have a look on how to do the same thing using an ASP.NET MVC web application.


An Empty MVC Application is always a good starting point

OK, Lets get started with an empty ASP.NET MVC Application.

  • Open Visual Studio (my version is 2017, 15.7.4).
  • Click File > New Project.
Select ans ASP.NET web application
  • Now Select Visual C# and then Web finally ASP.NET Web Application (.NET Framework) from the template list.
  • Give the project a proper name and its always a good practice to give a meaningful name. In this case I have chosen “MVCDemo.GraphAPI”.
  • Then click OK.
  • Now you should see this screen.
Selecting and Empty, MVC application
  • Select “Empty” in the templates and then check “MVC” under “references for:”.
  • Leave everything to their defaults and click OK.
  • Now you have an Empty MVC application.
Empty ASP.NET MVC Web Applicaiton

As I mentioned before we need to go through an Authentication process to access the Graph API. When you access graph API you need few things at our side. These information will tell Graph API you have all the permissions to access the Graph API.

A request header to a Graph API will look like this:

GET https://graph.microsoft.com/v1.0/me 
Authorization: Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw
Host: graph.microsoft.com

Yes, you are correct we need a Bearer Token for authorization process. Lets have a look how to grab this token using Azure AD and Application Identity. We will be using a Web Application to access the Graph API. So instead of User Id to access, we will be using Application Identity.

To do this we will have to create an Application under Azure AD. This will allow us to register our web application under Azure AD.

One more thing before we register our application at Azure AD. Go back to your web application.

  • Click on the Project name (MVCDemo.GraphAPI) Iin the Solution Explorer.
  • Open the Properties windows (F4 will do).
SSL Enabled set to True
  • Set SSL Enabled property to True.

Azure requires your web application URL always to be secured and to be under SSL. So its a good practice and must do when you deal with these sort applications.

Now lets get to Azure portal by typing this URL https://portal.azure.com in your favorite browser. And then after authentication process you should a page similar to this.

Azure Portal
  • Now in the left side blade scroll down and find the “Azure Active Directory” and click on it.
  • And then click “App Registrations”.
App Registrations blade
  • Click “New Application Registrations”.
  • Now give these information to your new application.

Note: Sign-on URL can be copied from your web application properties window. As shown below.

SSL URL
  • Click “Create”.
  • Your Azure AD Application should look like this.
Azure AD Application
  • Make sure you note down the values marked in red boxes. The Application ID and the Home Page url.
  • Now, lets go back to our Web Application and open the Web.config file and add these entries.
  • In between <appSettings></appSettings> add these parameters.

Make sure you have added values to your Tenant and Redirect Uri

Excellent, now we have registered our application at Azure AD and modified the Web.config file at our web application.

Now before we begin to add code, lets add these NuGet packages to our project.

  1. Microsoft.Owin.Security.OpenIdConnect
  2. Microsoft.IdentityModel.Protocol.Extensions
  3. Microsoft.Owin.Security.Cookies
  4. Microsoft.Owin.Host.SystemWeb

All other dependencies will be installed for you by NuGet Package Manager.

Adding Authentication Code

OK, now everything is setup to do some coding. Lets go ahead and add some code for authentication.

  • In the Solution Explorer, Click right mouse button on “App_Start” folder and select Add and then New Item.
  • From the New Item Dialog box.
OWIN Startup class
  • Select “Web” in the right side pane and “OWIN Startup class” in the middle pane. Give it name of “Startup.cs” and click “Add”.
  • Now lets add our namespaces required to build our authentication code.
  • Add the following namespaces on under using directives top of the code.
  • Now add these class level fields to your Startup.cs file.
  • Lets create a new public method called “ConfigureAuth” and add some code to it. And it should look like this.
ConfigureAuth method

As you see, we have created a method to handle the authentication process. In the line 3 and 4 we have setup the default authentication type as cookie authentication. Again in line 6 we have setup the OpenIdConnectAuthenticationOptions. These values are from our Web.config file. These values have the information from our Azure AD application. And then in line 12 we have captures the notification, if its a failure we have redirected it to a error page.

  • Call this “ConfigureAuth” method inside the Configuration method.

After all these steps your Startup.cs file should look like this.

Startup.cs

Now we have done with our authentication logic. Let’s add some user interface.

A Simple UI to test our code

OK, Lets get back to our web application and add a basic UI. Remember we started with an empty MVC project.

  • Lets go and select the “Controller” folder in the solution explorer.
  • Click the right mouse button on it and select Add and then select Controller.
  • In the dialog box select “MVC 5 Controller — Empty”.
  • And click Add.
  • Give it a name as “HomeController” and click Add.
  • Now you will see an empty HomeController with one Action method named Index.
  • Click right mouse button on the Index action method name and click “Add View”.
  • Leave all defaults and click “Add”.
  • Now open the “Index.cshtml” view file and replace with the following code.

Now lets add an AccountController to handled the sign in and sign out process.

  • Click right mouse button on the Controllers folder. And select “Add” and then “Controller”.
  • Follow the same steps you did to add the HomeController and name this controller as “AccountController”.
  • Lets add the SignIn and SignOut methods to our AccountController.cs and the code should look like this.
AccountController.cs

The code is straight forward, we have added code to sign in and sign out

Now lets execute and test our application by pressing F5. And make sure you are running under https with the URL copied from your project properties.

Home Screen

When you hit the Sign In link you should see bunch of screens that will ask you to login and give the permission to read your profile.

Sign In and Permissions

Excellent, now you are done with the authentication process. Lets go through the next steps of getting a token and give try on the Graph API.

  • Now open HomeController.cs.
  • You will need to add the following NuGet Package before you continue.

Microsoft.IdentityModel.Clients.ActiveDirectory

This package will enable your MVC web application to authenticate using AAD and request tokens. For more information about Azure Active Directory Authentication Library (ADAL) refer the below link.


One more important thing is required before we continue.

  1. Give permission to your AAD Application created at Azure Portal to access Graph API
  2. Generate an application key for that application. (This key is required when generate an access token to access Graph API)

Setting permission on AAD Application

AAD Application
  • Now click on “MVCGraphApiDemo”.
  • Next click on “Settings” and then “Required Permissions”.
Setting Permissions
  • Now inside “Required permissions” blade select Add > Select an API > Microsoft Graph.
  • And click the “Select” button.
  • Now you need to select the permission you required for the application to access using Graph API.
  • Under “Application Permissions” select “Read all users’ full profiles” (Cause we just going to read all users profiles only, thats enough for now).
  • Click “Select” and click “Done”.
  • Finally you need to click “Grant Permissions” and hit “Yes” to confirm.
Grant Permissions
  • Now, we need to create a key for our application.
  • Click “Keys” under “Settings” and give the key a name and a duration to expire.
Generate a key
  • Now hit “Save” and copy and paste the key in your Web.config file as in the code.

Make sure you copy this key. This key will disappear and this the only time you will allow to see this key.

<add key="ida:AppKey" value="<your_application_key>" />

Now lets get back to our code.

  • Add these references under using directives in the HomeController.cs
HomeContoller.cs usings
  • Now add these class level fields to access the values stored in the Web.config.
  • Create an action inside the HomeController.cs to access the Graph API end point.
  • Now add the following code on just next to open curly brackets of the actions method.

First we did on above code was to create the authority url where the authentication is happening. And then line 3 we have created an authentication context from our web application to the authority URI. Finally there is the authentication result to generate the token.

  • Lets create the code to get the token for Graph API. This code should be just next to the line 4 of above code.

As you see the AcquireTokenAsync requests token for Graph API and as the we have given the clientId and the appKey as the credentials. Now we are almost done.

In the above code we have created an HttpClient object and then in the line 2 we have created the request for Graph API. Line 3 is the important part. In this part we set the authorization header of our request. As you see its a Bearer token and and we have used the token from AuthenticationResult.

And in the line 6 we have stored the content from the response and finally in line 8 we stored the result in a ViewBag and this will read from our view.

The whole action should look like this. And make sure you decorate the action with an [Authorize] attribute.

Complete Users() action
  • Add a view to the Users action and replace the code with this code.
Users.cshtml
  • Finally modify the Index.cshtml file inside the Views/Home folder to look like this.
Index.cshtml

Excellent, We are all done here with coding. Lets do a quick F5 to test our application. Make sure you are running under https:// (see the red box)

Application launched under https://

Click the Sign in button and follow the sign in process and if all done you should greeted with this page.

Logged in page using AAD Authentication

Now press “Users” link, which will access the Graph API end point https://graph.microsoft.com/v1.0/users gets the results for you.

User View

Congratulations !!! You have successfully used one of the Graph APIs endpoints.

Conclusion

The aim of this tutorial is to introduce to the wonderful world of Microsoft Graph API. You can read more about Microsoft Graph API by clicking on the below link.

You can grab the full documentation here.

And you can grab the full working Visual Studio 2017 Solution here. (Make sure you have replaced the keys in Web.config file with your own)

Hav fun !!! Happy Coding 👍😎

Fiqri Ismail

Written by

Architect| Microsoft MVP | Community Leader | Speaker | Blogger | Photographer