Fetch access token to access Microsoft Graph API using MSAL.js (Microsoft Security Authentication Library)

MSAL (Microsoft Security Authentication Library) is a client side JavaScript library, helps developer to fetch access token for accessing Microsoft API’s, Microsoft Graph, Third party API’s (Google. Facebook) & User built custom API.

Its supports both 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 graph. You need to set it up App registration for your web App. login into your azure active directory portal using your work or school account.

Navigate to azure portal using the following address https://manage.windowsazure.com

After successfully logged in click on azure active directory

Azure Portal

Now click on App registration -> New app registration to register your web application

Provide the “Name” of your app and choose the supported account type there was three options you can connect using your office 365 account / Multi-tenant / Personal accounts

Am going to connect using single tenant option for account type

Finally provide the redirect URL to validate Web/Mobile&Desktop So now am going to choose web for my SharePoint application.

Once you click register you can get the unique client id / client secret for the app you registered it requires for configuring MSAL JS to validate and fetch access token so only we are able to play with Microsoft Graph API

Note: For mobile and desktop you can use the following redirect url suggested below on your azure portal

Now click on API Permissions If can see the Graph API permission by default to read the current logged in user profile “User.Read”

Now everything was fine from configuration section. Lets download the MSAL JS library and implement in SharePoint application CEWP (Content Editor) / Script editor web part

Download MSAL JS from the below link

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

var config = {
    auth: {
        clientId: "91ff15c6-0b25-4714-8600-1329a02e6d3a",
        authority: "https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com"
    },
    cache: {
        cacheLocation: "sessionStorage"        
    }
};

authority: In authority section if you does not have tenant ID. Please use the following url https://login.microsoftonline.com/common and if you have tenant provide the GUID of your tenant or yourdomain.microsoft,com

clientid: It’s mandatory you have it already from your azure portal app registration.

cacheLocation: You can store your access token in localStorage or sessionStorage

var graphConfig = {
    graphEndPoint: "https://graph.microsoft.com/v1.0/me"
};

Configure the Graph API Endpoint to read the current logged in user profile

Also you need to mention the permission scope like below

var requestPermissionScope = {
     scopes: ["user.read"]
};

You can add multiple permission as follows for an example ["user.read", "files.read"]

Initialize the MSAL configuration

var myMSALObj = new Msal.UserAgentApplication(config);

Now create to function named “RetrieveAccessToken” to acquire the token based on the permission scope

acquireTokenSilent: It helps to fetch the token of the current logged in user silently. If token expires it send request and automatically refresh the token.

function RetrieveAccessToken() { 

    myMSALObj.acquireTokenSilent(requestPermissionScope).then(function (result) {
 if(result != undefined){
var headers = new Headers();
    var bearer = "Bearer " + result.accessToken;
    headers.append("Authorization", bearer);
    var options = {
         method: "GET",
         headers: headers
    };

 fetch(graphConfig.graphEndPoint, options)
        .then(function(response) {
             //do something with response
             var data  = response.json()
             data.then(function(userinfo){
                console.log("resp", userinfo)
             })
              
        });
         
    }).catch(function (error) {
         console.log(error);
   });
  }     
}  

Full Code:

function RetrieveAccessToken() { 

    myMSALObj.acquireTokenSilent(requestPermissionScope).then(function (result) {
 if(result != undefined){
var headers = new Headers();
    var bearer = "Bearer " + result.accessToken;
    headers.append("Authorization", bearer);
    var options = {
         method: "GET",
         headers: headers
    };

 fetch(graphConfig.graphEndPoint, options)
        .then(function(response) {
             //do something with response
           
             if(response.status == 200){
                var data  = response.json();
                data.then(function(userinfo){
                    var printResponse = JSON.stringify(userinfo)
                    //Print the JSON string                      
                     $("#userInfo").html(printResponse)
                })
             }
        });
  }     
}  

Now see the browser console it returns the JSON object like below

Final result

In my upcoming articles let see about permissions,how to Integrate MSAL using spfx webparts.

Author Profile

Vinodh
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies.

His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration.

Awards :
Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
Technology Expertise :
SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview.
Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps.
Angular 5 with Bootstrap single page apps.
Typescript, JQuery and Javascript.
Micrsoft Flow and Powerapps.
Utilised :
Microsoft Graph API, SharePoint REST, SharePoint PnP JS.
Out of Box :
Consume Content search web parts for internet publishing sites using custom display templates.
Having knowledge on SharePoint workflows and SharePoint Designer workflows.
List customisation using JS Link, JSON Formatting.
Having knowledge in Active directory management services.
Create and configure service applications in SharePoint (MMS, UPSA, SSA).
Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *