0

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:

enter image description here

chennaiyan
  • 69
  • 1
  • 6
  • Are either of the calls of `messageParent` running? Put a console.log above each of them and see if that code path is running. – Rick Kirkham May 27 '20 at 17:39
  • @Rick.... I have attached console screen of Auth.html page and also none of messageParent getting logged...Let me please know if anything found....replace url i used as per scracth (../login.html) – chennaiyan May 28 '20 at 10:58
  • Also,alternatively if we configure our own identity server endpoints directly in scratch project https://github.com/OfficeDev/PnP-OfficeAddins/blob/master/Samples/auth/Office-Add-in-Microsoft-Graph-React/login/login.ts throwing service endpoint configuration error in task pane. We are not using any azure identity server. Or is it mandate to use the same? – chennaiyan May 28 '20 at 14:31
  • 1. msal.js only works with Azure AD. 2. Can you show your auth.html page so I can see how you are loading office.js? – Rick Kirkham May 28 '20 at 18:38
  • @Rick sorry...based on my conversation with you in the request https://stackoverflow.com/questions/61654587/how-to-use-refresh-token-to-get-new-access-token-in-excel-add-in-using-officejs.... i have been trying past two days to integrate with own identity server which is not registered with Azure AD... – chennaiyan May 29 '20 at 06:47
  • Kindly share your thought on this..Or which one we can we use to achieve both own identity server and refresh token logic..... – chennaiyan May 29 '20 at 11:41
  • If you are implementing your own Identity service, then all we can offer is the general advice in the article [Authorize external services ...](https://learn.microsoft.com/office/dev/add-ins/develop/auth-external-add-ins), especially the section about Libraries, some of which are libraries for implementing an Identity service. Also, if you design the service to allow it's login page to open in an iframe, then users can login directly in the task pane. You don't need a login dialog. – Rick Kirkham May 29 '20 at 16:32
  • @Rick... we already having own on premise server (identity server) through which we are trying to achieve refresh token logic either implicit flow or authorization code whatever it applies...also as i referred the libraries still trying each one which matches our login flow... – Muruga ananth Jun 01 '20 at 16:39
  • don't we have any other options to use either MSAL.js or ADAL.js with our requirement? – Muruga ananth Jun 01 '20 at 16:43
  • MSAL.js and ADAL.js were created specifically to work with Azure AD (that is what the "AD" in "ADAL" stands for.) From the first sentence of [Overview of MSAL](https://learn.microsoft.com/azure/active-directory/develop/msal-overview): "Microsoft Authentication Library (MSAL) enables developers to acquire tokens _from the Microsoft identity platform endpoint_ ..." They do not work with a custom identity provider. – Rick Kirkham Jun 01 '20 at 17:00

0 Answers0