I have built Excel add-in and wanted to implement login flow using MSAL.js for refresh token implementation. Below are the logic i tried.
Current Scenario:
Step 1: When I click login button as command event it will invoke taskpane.ts file as below coded.
Step 2: In task pane file i am trying to call UserAgentApplication in Auth.ts using Office.context.ui.displayDialogAsync
Step 3: I got result.status as succeeded but it is not getting into processLoginMessage method which is called using addEventHandler.
Expected Scenario:
Should call processLoginMessage method where it can get access token. Hence kindly let me know if anything i am missing.
Auth.ts
import * as msal from 'msal';
// The initialize function must be run each time a new page is loaded
Office.initialize = () => {
const config: msal.Configuration = {
auth: {
clientId: 'fc19440a-334e-471e-af53-a1c1f53c9226',
authority: 'https://login.microsoftonline.com/',
redirectUri: 'https://localhost:3000/taskpane.html'
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true
}
};
const userAgentApp: msal.UserAgentApplication = new msal.UserAgentApplication(config);
const authCallback = (error: msal.AuthError, response: msal.AuthResponse) => {
if (!error) {
if (response.tokenType === 'id_token') {
localStorage.setItem("loggedIn", "yes");
}
else {
// The tokenType is access_token, so send success message and token.
Office.context.ui.messageParent( JSON.stringify({ status: 'success', result : response.accessToken }) );
}
}
else {
const errorData: string = `errorMessage: ${error.errorCode}
message: ${error.errorMessage}
errorCode: ${error.stack}`;
Office.context.ui.messageParent( JSON.stringify({ status: 'failure', result: errorData }));
}
};
userAgentApp.handleRedirectCallback(authCallback);
const request: msal.AuthenticationParameters = {
scopes: ['user.read', 'files.read.all'],
};
if (localStorage.getItem("loggedIn") === "yes") {
userAgentApp.acquireTokenRedirect(request);
}
else {
userAgentApp.loginRedirect(request);
}
};
Taskpane.ts
Office.context.ui.displayDialogAsync(
url,
{height: 40, width: 30},
(result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
}
else {
loginDialog = result.value;
loginDialog.addEventHandler(Office.EventType.DialogMessageReceived, processLoginMessage);
}
}
);
function processLoginMessage(arg: any) {
if (arg != "jsonMessage") {
$(".loader").show();
var test = JSON.parse(arg.message).value.split("#")[1].split("&")[1].split("=");
let accessToken = test[1];
localStorage.setItem('accessToken', accessToken);
OfficeRuntime.storage.setItem('accessCustomToken', accessToken)
.then((result) => {
console.log(result);
}, (error) => {
console.log('Store error: ');
console.log(error);
});
loadProfiles();
$('#lstPrfId').show();
$("#lblprf").show();
dialog.close();
};
}
Screen Shot: