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.

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 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:

Finally, provide the redirect URL to validate Web/Mobile&Desktop Applications. In my case, am going to pick 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 configuring MSAL JS to validate and fetch the access token, then 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. I can see the Graph API permission by default to read the current logged in user profile “User.Read”

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
- var config = {
- auth: {
- clientId: "91ff15c6-0b25-4714-8600-1329a02e6d3a",
- authority: "https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com"
- },
- cache: {
- cacheLocation: "sessionStorage"
- }
- };
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.
- var graphConfig = {
- graphEndPoint: "https://graph.microsoft.com/v1.0/me"
- };
Configure the Graph API Endpoint to read the current logged in a user profile
Also, you need to mention the permission scope, like below:
- var requestPermissionScope = {
- scopes: ["user.read"]
- };
You can add multiple permissions as follows, for 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 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.
- 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, as shown below:

In my upcoming articles, let see with permissions how to Integrate MSAL using SPFx webparts.

Insaf AliPosted Oct 6, 2025, 12:02 PM
<script src="https://alcdn.msauth.net/browser/2.37.0/js/msal-browser.min.js"></script>//AZURE APP REGISTRATION ACCESS TOKEN START const msalConfig = { auth: { clientId: "Your Azure App Client ID", authority: "https://login.microsoftonline.com/Your Tenant ID", redirectUri: window.location.origin }, cache: { cacheLocation: "localStorage", storeAuthStateInCookie: true } }; const msalInstance = new msal.PublicClientApplication(msalConfig); let redirectHandlingPromise = null; async function initMSAL() { console.log('redirectHandlingPromise==>',redirectHandlingPromise) if (!redirectHandlingPromise) { redirectHandlingPromise = msalInstance.handleRedirectPromise(); } try { const response = await redirectHandlingPromise; if (response) { msalInstance.setActiveAccount(response.account); console.log("Redirect login successful:", response.account.username); } } catch (err) { console.error("handleRedirectPromise error:", err); } } function getAccount() { return msalInstance.getActiveAccount() || null; } async function login() { if (!getAccount()) { console.log("No active account, triggering loginRedirect..."); await msalInstance.loginRedirect({ scopes: ["https://your-tenant.sharepoint.com/AllSites.Read"] }); } } async function getAccessToken() { await initMSAL(); const account = getAccount(); if (!account) { await login(); return; } const request = { scopes: ["https://your-tenant.sharepoint.com/AllSites.Read"], account }; try { const response = await msalInstance.acquireTokenSilent(request); return response.accessToken; } catch (err) { console.warn("Silent token failed:", err); if (err instanceof msal.InteractionRequiredAuthError) { // Silent failed ? fallback to redirect console.log("Interaction required, redirecting..."); await msalInstance.acquireTokenRedirect(request); return; // redirect reloads page } else { throw err; } } } //AZURE APP REGISTRATION ACCESS TOKEN END
Rohan AmbokarPosted Sep 4, 2021, 4:00 PM
Hi , If a user logs in Microsoft Teams or Microsoft Office that is sufficient to get the tokens via Silent Authentication?
Mohsen AfshinPosted Mar 10, 2021, 9:14 AM
Thank you @Vinodh
Guest UserPosted Jul 21, 2020, 10:44 PM
Hi Vinodh, Nice article, I am trying to implement the same in a content editor webpart but getting CORS related error. Here is how i am using your code. <script type="text/javascript" src="/sites/Bot-Testing/Style%20Library/msal.js"></script> <script> var config = { auth: { clientId: "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", authority: "https://login.microsoftonline.com/xxxxxxxxxxxtest.onmicrosoft.com" }, cache: { cacheLocation: "sessionStorage" } }; var graphConfig = { graphEndPoint: "https://graph.microsoft.com/v1.0/me" }; var requestPermissionScope = { scopes: ["user.read"] }; var myMSALObj = new Msal.UserAgentApplication(config); 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) }) } }); } </script>??<br/> The error text in browser's console is this - Access to XMLHttpRequest at 'https://waconatm.officeapps.live.com/apc/trans.gif?a718df6579a9040dbe13faa205d98d6b' from origin 'https://xxxxxxxxxxxxxtest.sharepoint.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. waconatm.officeapps.live.com/apc/trans.gif?a718df6579a9040dbe13faa205d98d6b:1 Failed to load resource: net::ERR_FAILED