In order to access Microsoft Graph functionality, the first step is to authenticate and get the
access token using
MSAL, which will be discuss in this tutorial.
Install Microsoft.Identity.Client Package
Make sure you have added the
Microsoft.Identity.Client Nuget Package to your project.
To add the pacakge Go to
Nuget Package Manager >
Package Manager Console
Register your application to get Client Id
Make sure you register your application at the Microsoft Application Registration Portal and make a note of the Client id / Application Id. This Client Id will be required later when authenticating the user account.
1. Request Token
The very first step is to request a token. Once authenticated, the requesting application receives a token, which further can be used to query Microsoft Graph API. This token is used to access certain resources, such as user’s information, send emails, read OneNote notebooks and many other protected resources. We use the AcquireTokenAsync method to acquire the token interactively, as it displays the user sign-in window as seen below.
2. Receive and Parse Token
AcquireTokenAsync method returns an object of class
AuthenticationResult, which is stored in the variable authResult.
The actual token is stored in the
We check if the object returned by the function call AcquireTokenAsync is not null and then parse the object and display it accordingly.
3. Send GET Request with token
Once the token is received, we send a GET request attaching the access token as a header using the
The GET request is sent to the
https://graph.microsoft.com/v1.0/me Graph API Endpoint.
4. Display Graph API Response
The response from the Graph API call is returned in the form of
HttpResponseMessage object. We then serialize the HTTP content to a string using the
ReadAsStringAsync method. This string is then displayed on the UI.
You can find the source code at Github MSALAuthentication repo along with the
Visual Studio 2017 solution.
This is a very brief introduction to get you started using the MSAL and calling the Graph API. You can use the token received for further calls to the Graph API, as long as the token is in the header of the GET request. If you have any questions or concerns, feel free to leave a comment.