Written by

Jayakumar Balasubramaniam

Share

  

Category

see all categories
intranet as a service

Generate Graph API Access Token in SharePoint Provided hosted app

Graph API is a service offered by Microsoft to connect all the Microsoft 365 services and get advantage of the data in Office 365, Enterprise Mobility + Security and Windows 10. It helps us to build apps to interact with data of users just like calling other API services. 

The above picture says it all about Microsoft Graph API. Checkout Official Documentation of Microsoft Graph API to get to know more detail.

Register your app in Active Directory 

First step before generating access token to access Graph API is to register your app in Azure Active Directory. Where we can give permissions on which that app has access to. Follow the below steps to register the app in your Azure AD. 

1. Open Azure Portal and click All Services in the left side menu and search for Active Directory 

2. Click on Azure Active Directory and in the upcoming Azure Blade select App Registrations and click “+ New Application registration”.  

3. Fill the app name and register an app of type “Web app/API” as we are going to use this app in a web application. If you want to do the same in a mobile application you want to select the application type as “Native”. 

4. Open your registered app and click on Settings -> Properties - > Multi-tenanted as Yes. 

This setting allows this app to function on any tenant once the Tenant Admin approves the permission requested through this app which would help us in building a product kind of app which has to be work on tenant without being registered in each tenant individually. 

5. As like Provided hosted app’s Client Id and Client Secret for this app also we have same kind of setup. 

 

→ The Application Id highlighted in the above image is your Client ID 
→ We can generate Client Secret by using Keys option in settings pane.  
→ Give a description for your key and click save button system will generate a Key for you and make sure you copy it and save it some secured location once you see it. You cannot view it again for security reasons. 
→ The key generated here is the Client Secret of our registered application.

6. Now last step is adding the permission scopes that you would like to access through this app. 

Select the Microsoft Graph API and select the access which you want to grant to this application. 

So, we are done with the app registration part. 

Admin Consent 

Admin consent is nothing but the tenant administrator has to approve the permissions requested by the app through our last step. To get that done enter the below url in any browser and login using tenant admin credentials. 

In our case below is the url, 

https://login.microsoftonline.com/common/adminconsent?client_id=bcd80592-70f8-4ae7-a7a2-12662bd4afde&state=12345&redirect_uri=https://portal.office.com&sso_reload=true 

Make sure to replace the client id in the above URL which you got from your app. You will be prompted with below window 

Admin’s can review the Permissions requested and Accept the request. If it is declined by the admin or any changes you made to the permissions once after approving, Tenant admin needs to approve it again. 

We have completed all the basic steps needed to generate the Access token for Graph API in Provided hosted app. 

Generate the access token using below piece of code in your Provided hosted app by using the Client Id and Client Secret generated in our Azure App registration. The parameters has to be posted in as a form objects so the content type has to be “application/x-www-form-urlencoded”.  

private string getGraphAPIAccessToken() 

        { 

            string accessToken = string.Empty; 

            string result = string.Empty; 

            HttpClient client = null; 

            HttpRequestMessage httpRequestMessage = null; 

            HttpResponseMessage httpResponseMessage = null; 

            try 

            { 

                string tenantName = "tenantName.onmicrosoft.com"; 

                string requesrUrl = "https://login.microsoftonline.com/{TENANATNAME}/oauth2/token"; 

                requesrUrl = requesrUrl.Replace("{TENANATNAME}", tenantName); 

                var values = new Dictionary<string, string> 

                    { 

                       { "grant_type", "client_credentials" }, 

                       { "client_id", "bcd80592-70f8-4ae7-a7a2-12662bd4afde"}, 

                       { "client_secret", "YourSecretKey"}, 

                       { "resource","https://graph.microsoft.com" } 

                    }; 

                var content = new FormUrlEncodedContent(values); 

                client = new HttpClient(); 

                httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requesrUrl)); 

                client.BaseAddress = new Uri(requesrUrl); 

                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); 

                httpRequestMessage.Content = content; 

                httpResponseMessage = client.SendAsync(httpRequestMessage).Result; 

                result = httpResponseMessage.Content.ReadAsStringAsync().Result; 

                var resultObj = JsonConvert.DeserializeObject<dynamic>(result); 

                if (resultObj != null) 

                    accessToken = Convert.ToString(resultObj.access_token); 

            } 

            catch (Exception ex) 

            { 

                throw ex; 

            } 

            finally 

            { 

                client = null; 

                httpRequestMessage = null; 

                httpResponseMessage = null; 

            } 

            return accessToken; 

        } 

Finally, we have successfully generated the access token for Graph API in SharePoint Provided hosted app. 

If you have any questions/issues about this article, please let me know in comments.

Jayakumar Balasubramaniam

Written by Jayakumar Balasubramaniam

A technology evangelist working on Microsoft 365, SharePoint & Azure. Gets my hands dirty with latest and greatest of SharePoint, Azure & front-end frameworks. Currently working with “Hubfly – A unified digital workplace” as a Product Engineer. Getting in to the depth of the domain & technology, with my eyes for perfection, ensures that the product releases go right every time.