Insights Authenticate to the Graph API as a service

Authenticate to the Graph API as a service

Use the Graph API from a service or job with Application only permissions.

You may have a requirement to access the Graph API from a Web Job or service type client that is not running in the context of a logged in user.  This article shows the steps required to obtain an access token without requiring an interactive login. We will then use the token to retrieve a Share Point document as a PDF file.

Register an application in Azure Active Directory
The first step is to login to the Azure portal at https://portal.azure.com with an account that is a global administrator.
Navigate to the Active Directory blade and select the App registrations tab. This article uses the preview version of the registration blade.

Select the ‘Register an Application’ button.

Instructional screenshot of fields

Give the registration a name, make sure the type is ‘Web’ and provide a redirect url. Save this value as it will be needed later. There does not need to be an end point at this url, but the value here must match the value passed in on the authenticate call.

Save the Application (Client ID) value and the Directory (tenant id) value from this screen you will need these later. Then select the API permissions tab. Select ‘Add a permission’
Select the Microsoft Graph permission set.

Choose the appropriate permissions. Since this is a non-interactive authentication, only the Application permissions are relevant.  You’ll need to choose the permissions that your application needs to function, only permissions selected here and approved by the administrator will be available when the access token is requested.
 For this article we will retrieve a document from a Share Point library so the Sites – Read All permission is selected.

Press the ‘Grant/Revoke consent for xxx’ button to authorize the permissions for this application. This requires a global administrator to grant the access.

Finally, create a Client secret for this application. Select the Certificates and secrets tab then the ‘New Client secret’ button. Set your expiration as appropriate and make sure to copy the value as you won’t be able to retrieve it after you leave the blade.

At this point you should have the following values available for the code that will retrieve the access token:
Client Id – this is called Application Id or App Id in various contexts.
Client secret – if you place this value in an app settings value, you will need to change any ‘&’ characters to &
Tenant Id – this is also called Directory Id in some places
RedirectUri – the value you pass into the authentication must match the value you supplied when you created the registration. For a service application this url does not need to be an active endpoint.

Retrieve an Access Token without a user

This needs a nu-get package called Microsoft.Identity.Client installed. This is prerelease at this time, so you’d need to check the ‘include prerelease’ check box when you browse for the package in the NuGet tab.

This code assumes you have added all the required fields to your app.config or web.config file.
The scope https://graph.microsoft.com/.default requests the permissions that the administrator assigned to the application, you are not able to request additional permissions in non-interactive mode.
The error handling and async / await behavior has been omitted for clarity of the calls.
  public static string GetToken()
        {
            string clientId = ConfigurationManager.AppSettings[“ClientId”];
            string clientSecret = ConfigurationManager.AppSettings[“ClientSecret”];
            string redirectUri = ConfigurationManager.AppSettings[“RedirectUri”];
            string tenantId = ConfigurationManager.AppSettings[“TenantId”];

            string graphScope = “https://graph.microsoft.com/.default”;
            string AuthorityFormat = “https://login.microsoftonline.com/{0}/v2.0”;


            ConfidentialClientApplication clientApp = new ConfidentialClientApplication(
                clientId,
                string.Format(AuthorityFormat, tenantId),
                redirectUri,
                new ClientCredential(clientSecret),
                null,
                null);

            AuthenticationResult authResult = clientApp.AcquireTokenForClientAsync(new string[] {graphScope}).GetAwaiter().GetResult();

            return authResult.AccessToken;
        }

Call the Graph API with an application only token

Given the token from this method, here’s method that uses the Graph API to retrieve a document from a Share Point library as a PDF byte array.
The Domain value is the domain of the target Share Point site such as ‘contoso.sharepoint.com’.
The item Id is the ID of the document retrieved from the DriveItem object for the document. The path is the default document library for the default site at the specified domain.
The specifier ?format=pdf is the feature that allows you to get the document rendered as a PDF and not its native format which can be any of the Microsoft formats : csv, doc, docx, odp, ods, odt, pot, potm, potx, pps, ppsx, ppsxm, ppt, pptm, pptx, rtf, xls, xlsx.


     public static byte[]  GetPDFBytes(string token, string itemId)
        {
            string domain = ConfigurationManager.AppSettings[“Domain”];
            string path = “https://graph.microsoft.com/v1.0/sites/{0}/drive/items/{1}/content?format=pdf”;
            string url = string.Format(path, domain,itemId);

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
            request.Headers.Authorization = new AuthenticationHeaderValue(“Bearer”, token);
            HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
            byte [] bytes= response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
            return bytes;

        }

Explore the Graph API interactively

An easy way to discover items and test your URLs is a tool called Graph Explorer available as a web page at : https://developer.microsoft.com/en-us/graph/graph-explorer