Authenticate And Generate Microsoft Graph AccessToken AppID Using MS Graph .NET SDK

In this article, we will learn about how to authenticate and generate a Microsoft Graph AccessToken using AppId using ms graph dotnet sdk

Introduction

 
In this article, we learn about how to do simple authentication with the MS Graph(Microsoft Graph) API in DotNet or C# Conole App.
 

Description

 
Microsoft Graph is a Unified API. It is a Microsoft developer platform that connects multiple services and devices. Initially released in 2015, the Microsoft Graph builds on Office 365 APIs and allows developers to integrate their services with Microsoft products, including Windows, Office 365, Azure. 
 
Microsoft Graph is a Unified API meaning that single access token created using Microsoft app registration can be used with different service and it is CORS enabled, So No More issue in Browser(CORS issue might be you have faced using Sharepoint REST Request).
 
Recently, I came across a scenario to build a console app in which we have to Integrate Microsoft Graph API using C#.
 
Prerequisite
 
I assume that you have an idea of Registering Microsft Graph app in Microsoft developer platform or Azure Portal (App registration is free by the way, you only need a Microsoft account).
 
Once the app is registered and permission is configured you need to grant admin consent, and after that the app will work, otherwise it will give an unauthorized error.
 
For  more info, you can visit: https://docs.microsoft.com/en-us/graph/auth-v2-service
 
Nuget Package: See Below package file with the specific version as well.
  1. <packages>  
  2.   <package id="Microsoft.Graph" version="1.12.0" targetFramework="net45" />  
  3.   <package id="Microsoft.Graph.Core" version="1.12.0" targetFramework="net45" />  
  4.   <package id="Microsoft.Identity.Client" version="2.7.1" targetFramework="net45" />  
  5.   <package id="Newtonsoft.Json" version="6.0.1" targetFramework="net45" />  
  6. </packages>  
To Request Microsoft graph API from a console app, we need utility helper as below which is responsible for preparing all required configuration and setup GraphClient based on ClientId, Scope.
 
I have searched a lot for the running sample for MS Graph SDK  but most of them didn't work for me. It's an older version of SDK which is not working. I have found this code from Github repo and updated with the latest SDK,
 
AuthenticationHelper.cs 
  1. //Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.  
  2. //See LICENSE in the project root for license information.  
  3.   
  4. using System;  
  5. using System.Diagnostics;  
  6. using System.Net.Http.Headers;  
  7. using System.Net.Http;  
  8. using System.Linq;  
  9. using System.Threading.Tasks;  
  10. using Microsoft.Graph;  
  11. using Microsoft.Identity.Client;  
  12.   
  13. namespace MSGraphConsole  
  14. {  
  15.     public class AuthenticationHelper  
  16.     {  
  17.         // The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.  
  18.        // Add appId of your registered App  
  19.         static readonly string clientId = "51509718-3125-438f-z043-z70052846534";  
  20.         public static string[] Scopes = { "User.Read""Mail.Send""Files.ReadWrite" };  
  21.   
  22.         public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);  
  23.   
  24.         public static string TokenForUser = null;  
  25.         public static DateTimeOffset Expiration;  
  26.   
  27.         private static GraphServiceClient graphClient = null;  
  28.   
  29.         // Get an access token for the given context and resourced. An attempt is first made to   
  30.         // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.  
  31.         public static GraphServiceClient GetAuthenticatedClient()  
  32.         {  
  33.             if (graphClient == null)  
  34.             {  
  35.                 // Create Microsoft Graph client.  
  36.                 try  
  37.                 {  
  38.                     graphClient = new GraphServiceClient(  
  39.                         "https://graph.microsoft.com/v1.0",  
  40.                         new DelegateAuthenticationProvider(  
  41.                             async (requestMessage) =>  
  42.                             {  
  43.                                 var token = await GetTokenForUserAsync();  
  44.                                 requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);  
  45.                                 // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.  
  46.                                 requestMessage.Headers.Add("SampleID""MSGraphConsoleApp");  
  47.   
  48.                             }));  
  49.                     return graphClient;  
  50.                 }  
  51.   
  52.                 catch (Exception ex)  
  53.                 {  
  54.                     Debug.WriteLine("Could not create a graph client: " + ex.Message);  
  55.                 }  
  56.             }  
  57.   
  58.             return graphClient;  
  59.         }  
  60.   
  61.   
  62.         /// <summary>  
  63.         /// Get Token for User.  
  64.         /// </summary>  
  65.         /// <returns>Token for user.</returns>  
  66.         public static async Task<string> GetTokenForUserAsync()  
  67.         {  
  68.             AuthenticationResult authResult;  
  69.             try  
  70.             {  
  71.                 authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, IdentityClientApp.GetAccountsAsync().Result.First());  
  72.                 TokenForUser = authResult.AccessToken;  
  73.             }  
  74.   
  75.             catch (Exception)  
  76.             {  
  77.                 if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))  
  78.                 {  
  79.                     authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);  
  80.   
  81.                     TokenForUser = authResult.AccessToken;  
  82.                     Expiration = authResult.ExpiresOn;  
  83.                 }  
  84.             }  
  85.   
  86.             return TokenForUser;  
  87.         }  
  88.   
  89.         /// <summary>  
  90.         /// Signs the user out of the service.  
  91.         /// </summary>  
  92.         public static void SignOut()  
  93.         {  
  94.             foreach (var user in IdentityClientApp.GetAccountsAsync().Result)  
  95.             {  
  96.                 IdentityClientApp.RemoveAsync(user);  
  97.             }  
  98.             graphClient = null;  
  99.             TokenForUser = null;  
  100.   
  101.         }  
  102.   
  103.     }  
  104. }  
Program.cs
 
Before requesting graph API it will ask for authentication info; e.g. Modal popup from Microsoft. Once you enter valid credential a dialog will automatically be closed and you can see a graph request result as per below.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var graphClient=AuthenticationHelper.GetAuthenticatedClient();  
  6.         var Users = graphClient.Users.Request().Top(400).GetAsync().Result;  
  7.          
  8.         foreach (Microsoft.Graph.User item in Users)  
  9.         {  
  10.             Console.WriteLine(item.UserPrincipalName);  
  11.   
  12.         }  
  13.         Console.WriteLine(Users.Count);  
  14.         Console.ReadLine();  
  15.         Console.ReadKey();  
  16.     }  
  17. }  

Reference links

  • https://docs.microsoft.com/en-us/graph/auth-v2-service
  • https://github.com/microsoftgraph/msgraph-sdk-dotnet
Source code can be found at GitHub
 

Conclusion

 
In this article, we learned about how to achieve simple authentication with MS Graph API and get all user information.