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
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.
- <packages>
- <package id="Microsoft.Graph" version="1.12.0" targetFramework="net45" />
- <package id="Microsoft.Graph.Core" version="1.12.0" targetFramework="net45" />
- <package id="Microsoft.Identity.Client" version="2.7.1" targetFramework="net45" />
- <package id="Newtonsoft.Json" version="6.0.1" targetFramework="net45" />
- </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
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.
- class Program
- {
- static void Main(string[] args)
- {
- var graphClient=AuthenticationHelper.GetAuthenticatedClient();
- var Users = graphClient.Users.Request().Top(400).GetAsync().Result;
-
- foreach (Microsoft.Graph.User item in Users)
- {
- Console.WriteLine(item.UserPrincipalName);
-
- }
- Console.WriteLine(Users.Count);
- Console.ReadLine();
- Console.ReadKey();
- }
- }
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.