Accessing Microsoft Graph Data Using Azure AD Authentications From SPFx

Introduction

Let us see how to call Microsoft cloud data using Azure Active Directory authentications from SharePoint Framework components.

In my previous article, you have seen setting up Azure Active Directory application for granting the necessary permissions.

In this article, you will see how to make authenticated calls for pulling the SharePoint data from Microsoft graph. The authentications are provided using Azure Active Directory apps, explained in the previous article. These apps provide the necessary permissions to access the Graph data. Multiple sets of APIs are provided with necessary permissions before making the calls.

This will help to access the Microsoft data like O365 emails, events, calendar, user profile data, etc. with the help of Graph APIs.

In the sample, let us try to pull the users from Office 365 tenant using Graph APIs. Here, SPFx web parts are used along with the React Framework in the samples.

Steps Involved

Create the SPFx web part using the following command. Input the necessary details and create the web part.

yo @microsoft/sharepoint 

Two functions are used to pull the data. First, we need to get the request token for accessing the graph data. Once the request token is available, we can make necessary calls for getting the data from Office 365 portal using graph API.

In the first function, the necessary Azure client app details are stored. Using the available details, authentication URL is built. This authentication URL will be executed to get the request token from Azure. The page will be redirected, and request token will be available in the redirected page URL. 
 
Note

The client ID in the below code is copied from the app created in the previous article (app id). 
  1. public requestToken() {     
  2.   var clientId    = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';  // app id of Azure AD app  
  3.   var replyUrl    = 'https://nakkeerann.sharepoint.com/sites/spfx/_layouts/15/workbench.aspx';     
  4.   var resource = "https://graph.microsoft.com";    
  5.   var authServer  = 'https://login.microsoftonline.com/nakkeerann.onmicrosoft.com/oauth2/authorize?';      
  6.   var responseType = 'token';     
  7.     
  8.   var url = authServer +     
  9.             "response_type=" + encodeURI(responseType) + "&" +     
  10.             "client_id=" + encodeURI(clientId) + "&" +     
  11.             "resource=" + encodeURI(resource) + "&" +     
  12.             "redirect_uri=" + encodeURI(replyUrl);     
  13.   // Redirect to the URL, which will have access token on successful authentication    
  14.   window.location.assign(url);     
  15. }  
Once we get the token after page reloading, the token is sent as bearer token in the AJAX call for requesting the Graph data. In the response, necessary data will be sent back. For example, in this case, we are pulling the users' information.
  1. public getspdata(){  
  2.   // Token available, extract the data    
  3.   $.ajax({    
  4.       url: "https://graph.microsoft.com/v1.0/users",    
  5.       type: "GET",    
  6.       headers: { "Authorization""Bearer "+this.token },    
  7.       success: function (data) {    
  8.           data.value.forEach(element => {  
  9.             $("#users")[0].innerHTML += "<li>"+element.displayName+"</li>";     
  10.           });  
  11.             
  12.       },    
  13.       error: function (sender, args) {    
  14.           console.log("error");    
  15.       }    
  16.   });     
  17. }  
The whole React logic on SPFx components is shown below.
  1. export default class Graphdata extends React.Component<IGraphdataProps, void> {  
  2.   public token = null;  
  3.   public render(): React.ReactElement<IGraphdataProps> {  
  4.     this.token = this.getParameterByName('access_token');  
  5.     if(this.token == null){        
  6.       this.requestToken();  
  7.     }  
  8.     else{  
  9.       this.getspdata();  
  10.     }  
  11.     return (  
  12.       <div className={styles.helloWorld}>  
  13.         <ul id="users" className={styles.container}>  
  14.             
  15.         </ul>  
  16.       </div>  
  17.     );      
  18.   }  
  19.   public getspdata(){  
  20.     // Token available, extract the data    
  21.     $.ajax({    
  22.         url: "https://graph.microsoft.com/v1.0/users",    
  23.         type: "GET",    
  24.         headers: { "Authorization""Bearer "+this.token },    
  25.         success: function (data) {    
  26.             data.value.forEach(element => {  
  27.               $("#users")[0].innerHTML += "<li>"+element.displayName+"</li>";     
  28.             });  
  29.               
  30.         },    
  31.         error: function (sender, args) {    
  32.             console.log("error");    
  33.         }    
  34.     });     
  35.   }  
  36. // Extract the access token from the URL    
  37.   public getParameterByName(name) {    
  38.     var url = window.location.href;    
  39.     name = name.replace(/[\[\]]/g, "\\$&");    
  40.     var regex = new RegExp("[?&#]" + name + "(=([^&#]*)|&|#|$)"),    
  41.         results = regex.exec(url);    
  42.     if (!results) return null;    
  43.     if (!results[2]) return '';    
  44.     return decodeURIComponent(results[2].replace(/\+/g, " "));    
  45.   }    
  46.     
  47. // Get the token using the redirect URL    
  48.   public requestToken() {     
  49.     var clientId    = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'// app id of Azure AD app  
  50.     var replyUrl    = 'https://nakkeerann.sharepoint.com/sites/spfx/_layouts/15/workbench.aspx';     
  51.     var resource = "https://graph.microsoft.com";    
  52.     var authServer  = 'https://login.microsoftonline.com/nakkeerann.onmicrosoft.com/oauth2/authorize?';      
  53.     var responseType = 'token';     
  54.       
  55.     var url = authServer +     
  56.               "response_type=" + encodeURI(responseType) + "&" +     
  57.               "client_id=" + encodeURI(clientId) + "&" +     
  58.               "resource=" + encodeURI(resource) + "&" +     
  59.               "redirect_uri=" + encodeURI(replyUrl);     
  60.     // Redirect to the URL, which will have access token on successful authentication    
  61.     window.location.assign(url);     
  62.   }     
  63. }  
The following snapshot shows the SharePoint page along with the Graph data rendered. This shows the users from the current Office 365 tenant.


Summary

Thus, you have seen how to extract the Microsoft cloud data (Office 365 users) from Office 365 using Graph APIs on SharePoint Framework components. Azure Active Directory and Client applications are used for setting the necessary permissions for APIs and authentications, which was explained in the previous article.

Up Next
    Ebook Download
    View all
    Learn
    View all