Fetch An Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)

Introduction 

 
MSAL (Microsoft Security Authentication Library) is a client-side JavaScript library that helps developers fetch access token to access Microsoft APIs, Microsoft Graph, Third-party APIs (Google. Facebook) & User built custom APIs.
 
Its supports Mobile, Web, and Desktop Based Applications.
 
It works for both Microsoft Work Accounts and Personal accounts through V 2.0 Endpoint.
 
If you want to connect your web application to the graph, you need to set it up with App registration for your web App. Log in to your Azure Active Directory portal using your work or school account.
 
Navigate to the Azure portal using the following address: https://manage.windowsazure.com
 
After successfully logging in, click on Azure Active Directory.
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Now click on App registration -> New app registration to register your web application
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Provide the “Name” of your app and choose the supported account type. There are three options, you can connect using your office 365 account/Multi-tenant/Personal accounts.
 
I am going to connect using the single tenant option as the account type:
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Finally, provide the redirect URL to validate Web/Mobile&Desktop Applications. In my case, am going to pick web for my SharePoint application.
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Once you click register, you can get the unique client id/client secret for the app you registered. It requires configuring MSAL JS to validate and fetch the access token, then we are able to play with Microsoft Graph API.
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Note
For mobile and desktop, you can use the following redirect URL suggested below on your Azure portal.
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
Now click on API Permissions. I can see the Graph API permission by default to read the current logged in user profile “User.Read”
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
Everything was fine from the configuration section. Let's download the MSAL JS library and implement it in the SharePoint application CEWP (Content Editor)/Script editor web part
 
Download MSAL JS from the below link:
 
FROM CDN -  https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.js
 
Create a object to store the configuration and storage option to store the access token in local storage or session storage.
  1. var config = {  
  2.     auth: {  
  3.         clientId: "91ff15c6-0b25-4714-8600-1329a02e6d3a",  
  4.         authority: "https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com"  
  5.     },  
  6.     cache: {  
  7.         cacheLocation: "sessionStorage"          
  8.     }  
  9. };  
authority
 
In the authority section, if you do not have tenant ID, please use the following URL: https://login.microsoftonline.com/common. If you have the tenant, provide the GUID of your tenant or yourdomain.microsoft.com
 
clientid
 
It’s mandatory that you have it already from your azure portal app registration.
 
cacheLocation
 
You can store your access token in localStorage or sessionStorage.
  1. var graphConfig = {  
  2.     graphEndPoint: "https://graph.microsoft.com/v1.0/me"  
  3. };  
Configure the Graph API Endpoint to read the current logged in a user profile
 
Also, you need to mention the permission scope, like below:
  1. var requestPermissionScope = {  
  2.      scopes: ["user.read"]  
  3. };   
You can add multiple permissions as follows, for example: ["user.read", "files.read"]
 
Initialize the MSAL configuration:
  1. var myMSALObj = new Msal.UserAgentApplication(config);  
Now create to function named “RetrieveAccessToken” to acquire the token based on permission scope.
 
acquireTokenSilent
 
It helps to fetch the token of the current logged in user silently. If the token expires, it sends a request and automatically refreshes the token.
  1. function RetrieveAccessToken() {   
  2.   
  3.     myMSALObj.acquireTokenSilent(requestPermissionScope).then(function (result) {  
  4.  if(result != undefined){  
  5. var headers = new Headers();  
  6.     var bearer = "Bearer " + result.accessToken;  
  7.     headers.append("Authorization", bearer);  
  8.     var options = {  
  9.          method: "GET",  
  10.          headers: headers  
  11.     };  
  12.   
  13.  fetch(graphConfig.graphEndPoint, options)  
  14.         .then(function(response) {  
  15.              //do something with response  
  16.              var data  = response.json()  
  17.              data.then(function(userinfo){  
  18.                 console.log("resp", userinfo)  
  19.              })  
  20.                 
  21.         });  
  22.            
  23.     }).catch(function (error) {  
  24.          console.log(error);  
  25.    });  
  26.   }       
  27. }    
Full Code
  1. function RetrieveAccessToken() {   
  2.   
  3.     myMSALObj.acquireTokenSilent(requestPermissionScope).then(function (result) {  
  4.  if(result != undefined){  
  5. var headers = new Headers();  
  6.     var bearer = "Bearer " + result.accessToken;  
  7.     headers.append("Authorization", bearer);  
  8.     var options = {  
  9.          method: "GET",  
  10.          headers: headers  
  11.     };  
  12.   
  13.  fetch(graphConfig.graphEndPoint, options)  
  14.         .then(function(response) {  
  15.              //do something with response  
  16.              
  17.              if(response.status == 200){  
  18.                 var data  = response.json();  
  19.                 data.then(function(userinfo){  
  20.                     var printResponse = JSON.stringify(userinfo)  
  21.                     //Print the JSON string                        
  22.                      $("#userInfo").html(printResponse)  
  23.                 })  
  24.              }  
  25.         });  
  26.   }       
  27. }    
Now see the browser console. It returns the JSON object, as shown below:
 
Fetch Access Token To Access Microsoft Graph API Using Msal.JS (Microsoft Security Authentication Library)
 
In my upcoming articles, let see with permissions how to Integrate MSAL using SPFx webparts.