How to get Azure AD app-only access token and using Microsoft graph Api to interact with Azure Active Directory

get Azure AD app-only access token using Microsoft graph Api
SharePoint deveopment training course

This Microsoft graph API tutorial, we will discuss how to get Azure AD app-only access token and using Microsoft graph Api to interact with Azure Active Directory.

Get Azure AD app-only access token using Microsoft Graph Api

Follow below steps to get Azure AD app-only access token and using Microsoft graph Api to interact with Azure Active Directory.

Step-1: Create an App Service in https://portal.azure.com

Step-2: Grant Required Permissions for the same.

Step-3: Get Client id, Tenant Id & Client Secret as follows

Go to azure portal → Azure Active Directory→ App Registrations → Click on ur app → Note down clientid, clientsecret.

Go to Visual Studio 2017, File → New Project → ConsoleApp

Include the following in App.config file

<appSettings>
    <add key="Tenant" value="tenant.onmicrosoft.com" />   
    <add key="ClientId" value=" " />
    <add key="ClientSecret" value=" " />
    <add key="Resource" value="https://graph.microsoft.com/" />
  </appSettings>

Add following nuget packages

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Specialized;
using System.Configuration;

Add the below code to generate Token
{
    class Program
    {
        public static void Main()
        {
           var result=GetAccess();
            Console.ReadKey();
        }
        public static async Task GetAccess()
        {
            try
            {
                //var token = await AppAuthenticationAsync();
                var token = await HttpAppAuthenticationAsync();

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                    var user = "user@tenant.onmicrosoft.com";
                    var userExist = await DoesUserExistsAsync(client, user);

                    Console.WriteLine($"Does user exists?  {userExist}");

                    if (userExist)
                    {
                        var WebTitle = await GetWebTitle(client, string.Empty);

                        Console.WriteLine($"Does WebTitle Found?  {WebTitle}");
                    }
                }
            }
            catch (Exception ex)
            {
                // important to log the exception if any because it will tell you what went wrong
                Console.WriteLine(ex.Message);
            }
        }
   
        private static async Task<string> HttpAppAuthenticationAsync()
        {
            //  Constants - get it from app config
            var tenant = ConfigurationManager.AppSettings["Tenant"];
            var resource = ConfigurationManager.AppSettings["Resource"];
            var clientID = ConfigurationManager.AppSettings["ClientId"];
            var secret = ConfigurationManager.AppSettings["ClientSecret"];
            using (var webClient = new WebClient())
            {
                var requestParameters = new NameValueCollection();
                requestParameters.Add("resource", resource);
                requestParameters.Add("client_id", clientID);
                requestParameters.Add("grant_type", "client_credentials");
                requestParameters.Add("client_secret", secret);

                var url = $"https://login.microsoftonline.com/" + tenant + "/oauth2/token";
                var responsebytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
                var responsebody = Encoding.UTF8.GetString(responsebytes);
                var obj = JsonConvert.DeserializeObject<JObject>(responsebody);
                var token = obj["access_token"].Value<string>();

                return token;
            }
        }

        private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user)
        {
            try
            {
                var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}");
                return true;
            }
            catch (HttpRequestException)
            {
                return false;
            }
        }


        private static async Task<bool> GetWebTitle(HttpClient client, string siteID)
        {
            siteID = " ";
            try
            {
                var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/sites/{siteID}");

                return true;
            }
            catch (HttpRequestException)
            {
                return false;
            }
        }
    }
}

You may like following Azure tutorials:

Hope this Azure tutorial explains, how to get Azure AD app-only access token and using Microsoft graph Api to interact with Azure Active Directory.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope