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'; 

  3.  // app id of Azure AD app

  4. var replyUrl    = 'https://nakkeerann.sharepoint.com/sites/spfx/_layouts/15/workbench.aspx';     

  5. var resource = "https://graph.microsoft.com";    

  6. var authServer  = 'https://login.microsoftonline.com/nakkeerann.onmicrosoft.com/oauth2/authorize?';      

  7. var responseType = 'token';     

  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     window.location.assign(url);     

  14. }  


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. error: function (sender, args) {              

  13. console.log("error");          

  14. }      

  15. });     

  16. }  

The whole React logic on SPFx components is shown below.

  1. export default class Graphdata extends React.Component<IGraphdataProps, void

  2. {  

  3. public token = null;  

  4. public render(): React.ReactElement<IGraphdataProps> 

  5. {  

  6. this.token = this.getParameterByName('access_token');  

  7. if(this.token == null){        

  8. this.requestToken();      

  9. }  

  10. else{  

  11. this.getspdata();      

  12. }  

  13. return (        

  14. <div className={styles.helloWorld}>          

  15. <ul id="users" className={styles.container}>           

  16. </ul>        

  17. </div>      

  18. );        

  19. }  

  20. public getspdata(){  

  21. // Token available, extract the data       

  22. $.ajax({            

  23. url: "https://graph.microsoft.com/v1.0/users",            

  24. type: "GET",            

  25. headers: { "Authorization": "Bearer "+this.token },            

  26. success: function (data) {                

  27. data.value.forEach(element => {                

  28. $("#users")[0].innerHTML += "<li>"+element.displayName+"</li>";                 

  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. // Get the token using the redirect URL  

  47. public requestToken() {     

  48. var clientId    = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; 

  49. // 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. var url = authServer +     

  55. "response_type=" + encodeURI(responseType) + "&" +     

  56. "client_id=" + encodeURI(clientId) + "&" +     

  57. "resource=" + encodeURI(resource) + "&" +     

  58. "redirect_uri=" + encodeURI(replyUrl);     

  59. // Redirect to the URL, which will have access token on successful authentication       window.location.assign(url);       

  60. }     

  61. }  


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.