OfficeDev / microsoft-teams-library-js

JavaScript library for use by Microsoft Teams apps
https://docs.microsoft.com/microsoftteams/platform/
Other
426 stars 194 forks source link

[1.8.0, 1.10.0, 1.11.3-beta] initialize() and getContext not firing in popup window Microsoft Teams Version 1.4.00.16575(64bit desktop) #617

Open CalamityLorenzo opened 3 years ago

CalamityLorenzo commented 3 years ago

My application has a popup window to handle an MSAL login. The detects we are in teams desktop and calls the following

 microsoftTeams.initialize();
        microsoftTeams.authentication.authenticate({
            url: ReflektPaths.LoginPopUp,
            width: 455,
            height: 505,
            successCallback: (result: string | undefined) => {
                console.log("success desktop login");
                if (result) { // store all the details back in the account manager.
                    console.log(result);
                    const { id_token, session_state } = JSON.parse(result)
                    acm.reflektLoginProcess(result);
                    acm.reflektIdToken(id_token, session_state);
                }
                window.location.assign(ReflektPaths.SignedIn);
            },
            failureCallback: (err?: string | undefined) => {
                console.log("Teams Login error.");
                var anyObj = JSON.parse(err as string) as any;
                const errObj = {.....

In the pop-up the following code is called.

    private login() {
        microsoftTeams.initialize();
        microsoftTeams.getContext((ctx) => this.teamsLogin(ctx.loginHint));
    }

This has worked fine for two years. It starts a login redirect flow and returns the token, for processing etc etc.

However now, when the pop-up is launched, the microsoftTeams.initialize() does nothing, and just falls through. If I add a callback : microsoftTeams.initialize(()=>console.log('weee')); This does not get triggered. As this doesn't fire, then getContext() does not either. If I remove the microftTeams.initalize() call nothing happens. If I add a delay between the initalize() call and the getContext() method, nothing happens. If I drop microsoftTeams object to the console (console.log(microsoftTeams), it's a complete object replete with methods, lists of error codes etc.

Has something changed, to disallow init in the pop-up window?

ghost commented 3 years ago

Hi CalamityLorenzo! Thank you for bringing this issue to our attention. We will investigate and if we require further information we will reach out in one business day. Please use this link to escalate if you don't get replies.

Best regards, Teams Platform

CalamityLorenzo commented 3 years ago

It works as expected in Teams 1.4.00.11161

malsabbagh commented 3 years ago

I noticed this issue as well in MS Desktop Teams on Windows version 1.4.00.19572 and Mac version 1.4.00.22265

We have a callback using microsoftTeams.initialize(() => {state=ready}); The callback is never called. It only happens within a popup context.

This works fine in web using Chrome/Firefox/Edge.

malsabbagh commented 3 years ago

Just as a side note, I don't believe this is related to the version of TeamsJS. I had version v1.5.2 and I switched to v1.10.0 and both have this issue. It looks to me, it is MS Teams Desktop app issue.

malsabbagh commented 3 years ago

Another small update, after a few restarts of MS Teams Desktop app for Mac, it started working again. It feels like a race condition of some sort. I couldn't get Window MS Teams Desktop app to work.

smauglys commented 3 years ago

Hi, we seem to have the same issue, but different people on same Teams version have different results. For some it works as it used to work, but for me and another person it doesn't fire anymore.

Our Teams App is using 1.6.0 version of TeamsJS.

<html>
  <head>
      <title>Login start</title>
      <script src="https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js"></script>
  </head>
  <body>
      <script>
              microsoftTeams.initialize();

              // Get the tab context, and use the information to navigate to Azure AD login page
              microsoftTeams.getContext(function (context) {
                     // This does not get fired.
              });
      </script>
  </body>
</html>

Any ideas what is wrong and how to fix this issue?

ChetanSharma-msft commented 3 years ago

@smauglys - I have tested the above shared code by you and it's working for us using 1.6.0 version of TeamsJS. We have tested with Microsoft Teams Version 1.4.00.16575 (64-bit). It was last updated on 7/9/2021.

Could you please reverify from your end once.

smauglys commented 3 years ago

@smauglys - I have tested the above shared code by you and it's working for us using 1.6.0 version of TeamsJS. We have tested with Microsoft Teams Version 1.4.00.16575 (64-bit). It was last updated on 7/9/2021.

Could you please reverify from your end once.

Hi, I can confirm it still does not work on one machine, but works on my other pc. Both run Windows 10. Both use the exact same App that is published to Teams.

  1. PC1: Teams version: 64bit, You have Microsoft Teams Version 1.4.00.22472 (64-bit). It was last updated on 2021-08-16. The authentication dialog opens, but gets stuck as getContext is not working. The code above is NOT working.

  2. PC2: Teams version: 64bit, You have Microsoft Teams Version 1.4.00.22472 (64-bit). It was last updated on 2021-08-17. The code above is working as expected, getContext works.

The behavior is a bit random on other developer machines (don't know the exact Teams versions, but app is the same), but in most cases it works.

Maybe I can add more code and when it is called to give more context:

  1. We open a Teams microsoftTeams.authentication.authenticate authentication dialog:
    microsoftTeams.authentication.authenticate({
    url: window.location.origin + "/....../TeamsAuthStart.html#res=" + resource,
    width: 600,
    height: 535,
    successCallback: function (result) {
        resolve(result);
    },
    failureCallback: function (reason) {
        reject(reason);
    }
    });
  2. Inside that TeamsAuthStart.html which was used to open the login dialog, we run the microsoftTeams.getContext as show in my previous post:

    <html>
    <head>
      <title>Login start</title>
      <script src="https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js"></script>
    </head>
    <body>
      <script>
              microsoftTeams.initialize();
    
              // Get the tab context, and use the information to navigate to Azure AD login page
              microsoftTeams.getContext(function (context) {
                     // This does not get fired.
              });
      </script>
    </body>
    </html>
CalamityLorenzo commented 3 years ago

I discovered, if you downgrade your version of teams and let the app upgrade itself this clears whatever the issue is and the calls start working again.

smauglys commented 3 years ago

I discovered, if you downgrade your version of teams and let the app upgrade itself this clears whatever the issue is and the calls start working again.

How to downgrade?

CalamityLorenzo commented 3 years ago

https://microsoft-teams.en.uptodown.com/windows/versions That's one place that has an archive of older versions, install one of them. I rolled back to the previous version that worked. I don't remember if I uninstalled first.

smauglys commented 3 years ago

https://microsoft-teams.en.uptodown.com/windows/versions That's one place that has an archive of older versions, install one of them. I rolled back to the previous version that worked. I don't remember if I uninstalled first.

Downgrading Teams to 1.3.x worked, but after it updated to 1.4.00.22472 (64-bit), issue is back.

ChetanSharma-msft commented 3 years ago

@smauglys - Could you please try updating your Teams SDK or TeamsJS version & test it with latest Teams version.

smauglys commented 3 years ago

@smauglys - Could you please try updating your Teams SDK or TeamsJS version & test it with latest Teams version.

I did update to version https://statics.teams.cdn.office.net/sdk/v1.10.0/js/MicrosoftTeams.min.js Still have the same issue.

smauglys commented 3 years ago

Also rewritten the code to not require to get the context, but pass the parameters, then I am getting a different issue which is this: 1) After microsoftTeams.authentication.notifySuccess in the authFinish popup 2) cancelledByUser is received in the callback of microsoftTeams.authentication.authenticate failureCallback method

https://github.com/OfficeDev/microsoft-teams-library-js/issues/173#issuecomment-575311411

Also mentioned in the comment: https://stackoverflow.com/questions/68657539/microsoft-teams-auth-flow-cross-origin-error

Maybe these both problems are related?

ChetanSharma-msft commented 3 years ago

@smauglys - Could you please share the manifest file and codebase if possible here or via mail (microsoftteamsdev@microsoft.com) so that we can test it from our end.

dpraul commented 3 years ago

I am experiencing a similar or identical issue, where initialize will never fulfill its callback from within the auth popup launched via authentication.authenticate on the desktop client. The issue is occurring on the most recent version of Teams and on the developer preview version (1.4.00.22472). @microsoft/teams-js version 1.10.0. The issue is inconsistent, though - only two of our users have experienced it, and it is only on some devices. Luckily, one of those users is me - the auth popup works just fine on one of my machines, but on another the issue occurs.

Here is a snippet of the code that pertains to launching the auth popup:

class MicrosoftTeamsService {
  private teamsSdk$: Observable<MicrosoftTeamsJsModule> = this.microsoftTeamsSdkService.teamsJs$.pipe(
    mergeMap((teamsJs) => new Observable<MicrosoftTeamsJsModule>((observer) => {
      teamsJs.initialize(() => {
        // this never gets called within the auth popup... sometimes
        observer.next(teamsJs);
        observer.complete();
      });
    })),
    shareReplay({ bufferSize: 1, refCount: false })
  );

  authorizeInPopup(): Observable<string> {
    return this.teamsSdk$.pipe(
      first(),
      switchMap((teams) => new Observable<string>((observer) => {
        teams.authentication.authenticate({
          url: `${this.window.location.origin}${MicrosoftTeamsService.teamsAuthUrl}`,
          width: 400,
          height: 600,
          successCallback: (token) => {
            observer.next(token);
            observer.complete();
          },
          failureCallback: (err) => {
            observer.error(new Error(err));
          },
        });
      }))
    );
  }
}

And then here is the code that occurs in the auth popup itself:


class MicrosoftTeamsService {
  notifyAuthenticationSuccess(token: string): Observable<never> {
    return this.teamsSdk$.pipe(
      first(),
      map((teams) => {
        teams.authentication.notifySuccess(token);
      }),
      delay(5000),
      mergeMap(() => {
        // notifySuccess should close the window, but sometimes it doesn't
        // in case it doesn't, manually close it!
        this.window.close();
        return NEVER;
      })
    );
  }
}
ChetanSharma-msft commented 3 years ago

We are also checking on this issue internally and get back to you if find any resolution for it.

olexu commented 2 years ago

Also rewritten the code to not require to get the context, but pass the parameters, then I am getting a different issue which is this:

1. After **microsoftTeams.authentication.notifySuccess** in the authFinish popup

2. **cancelledByUser** is received in the callback of **microsoftTeams.authentication.authenticate** **failureCallback** method

#173 (comment)

Also mentioned in the comment: https://stackoverflow.com/questions/68657539/microsoft-teams-auth-flow-cross-origin-error

Maybe these both problems are related?

We are experiencing the same issue. Context never initialized in popup. If we try to call notifySuccess without context - popup closed with "CanceledByUser" error.

This happen only in Teams Desktop app for random user/tenants

PodgeHeavin commented 2 years ago

I have had the smae issue reported to us by numerous customers in production. We have a published tab app that our cusomters cannot authenticate properly through the desktop app, we are currently asking them to use it via the web app, which is not sustainable.

The popup window for the authentication does not get the context returned to it. This means that the tenantId is unable to build the log in search string.

The issue is only prevelant in teams desktop but not the browsers version

OS: Windows 10 Teams version: 1.4.00.22976 (64-bit). SDK version: 1.10.0

Code triggering popup:

    await new Promise<void>((resolve, reject) => {
          MicrosoftTeams.authentication.authenticate({
            url: window.location.origin + '/teams/auth-start',
            width: 600,
            height: 700,
            successCallback: () => resolve(),
            failureCallback: reject
          });
        });

Code inside popup:

MicrosoftTeams.getContext((context) => {

    // Generate random state string and store it, so we can verify it in the callback
    const state = uuid();

    localStorage.setItem(Constants.LocalStorageStateKey, JSON.stringify({ state, feature: this.feature}));

    // See https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-implicit
    // for documentation on these query parameters
    const queryParams: URLSearchParams = new URLSearchParams({
      client_id: globalConfig?.clientId,
      response_type: 'id_token token',
      response_mode: 'fragment',
      scope:  globalConfig.authScopes,
      redirect_uri: window.location.origin + '/teams/auth-end',
      nonce: uuid(),
      state: state,
      login_hint: context.loginHint
    });

    const authorizeEndpoint = `https://login.microsoftonline.com/${context.tid}/oauth2/v2.0/authorize?${queryParams.toString()}`;

    // Go to the AzureAD authorization endpoint
    window.location.assign(authorizeEndpoint);
});
ChetanSharma-msft commented 2 years ago

@smauglys, @dpraul and all, We have raised a internal bug for it and engineering team is looking into it. We do not have exact ETA to share but we are tracking it closely.

ghost commented 2 years ago

Adding another related instance where microsoftTeams.getContext(callback) isn't completing for one of our customers in the Desktop app but works fine for them in the browser app:

In this case, the failure is happening during tab configuration (the page defined in our app manifest's configurableTabs.configurationUrl property).

smauglys commented 2 years ago

@smauglys, @dpraul and all, We have raised a internal bug for it and engineering team is looking into it. We do not have exact ETA to share but we are tracking it closely.

Thanks for the update, just to let you know, this is still happening on one of my machines, so if you need me to test anything (a new build/etc), please let me know.

ChetanSharma-msft commented 2 years ago

@smauglys - We will let you know if we get any updates from engineering team.

rolandbodenstaff commented 2 years ago

@v-chetsh Do you have any update from the engineering team about this issue? We are experiencing the same issue.

ChetanSharma-msft commented 2 years ago

@rolandbodenstaff - I will confirm and let you know.

ChetanSharma-msft commented 2 years ago

I have confirmed with engineering team and they are still investigating the issue.

PodgeHeavin commented 2 years ago

@v-chetsh This is a production issue and was raised on July 15th, when can we expect a fix? This is causing issues for many applications by the looks of it.

ChetanSharma-msft commented 2 years ago

Hello All, This issue investigation is in-progress. We have a ICM raised for it.

PodgeHeavin commented 2 years ago

What is the status of the ICM on this??

ChetanSharma-msft commented 2 years ago

@PodgeHeavin - Engineering team is still doing investigation on this issue. We will inform you once we get any updates on it.

PodgeHeavin commented 2 years ago

Surely there is some progress on this? It has been opened since July!!!

ChetanSharma-msft commented 2 years ago

@CalamityLorenzo, @PodgeHeavin - We got an update from engineering team on similar kind of issue. Please check here: https://github.com/OfficeDev/microsoft-teams-library-js/issues/629

HunaidHanfee-MSFT commented 2 years ago

We have got feedback from a customer that after updating the Teams desktop client to the latest the issue is no longer persists. Could you please try updating the Teams desktop client and check it once?

Please let us know if you are still facing the issue.

Thanks

smauglys commented 2 years ago

Tried to update today, did not receive any update, version is: You have Microsoft Teams Version 1.4.00.31569 (64-bit). It was last updated on 2021-11-15. And still having the same issue. Is there a newer version where this is fixed?

ChetanSharma-msft commented 2 years ago

@smauglys - Looks like it's the latest version only. Could you please share your repro steps and error logs, if any. Also please share the sample code, if possible. So that we can check it from our end.

smauglys commented 2 years ago

I have produced all code samples and steps and everything above on this issue, just look for my name above. I have also downloaded the latest version and installed, and the issues is still there. You have Microsoft Teams Version 1.4.00.31569 (64-bit). It was last updated on 2021-12-01.

ChetanSharma-msft commented 2 years ago

@smauglys - We have tested it in our windows desktop PC's and it was working fine for us. Could you please check it in another PC whether it's working fine or not.

Also could you please delete Desktop Teams client cache, blob_storage, GPUCache etc. and try it once. %appdata%\microsoft\teams\cache %appdata%\microsoft\teams\blob_storage %appdata%\microsoft\teams\GPUCache

smauglys commented 2 years ago

Deleted the 3 folders, did not help, still stuck. This does work on another machine that I have, please read above, its still the same as it was.

ChetanSharma-msft commented 2 years ago

@smauglys - Could you please check here for suggested workaround: https://github.com/OfficeDev/microsoft-teams-library-js/issues/629#issuecomment-975926875

smauglys commented 2 years ago

@smauglys - Could you please check here for suggested workaround: #629 (comment)

Sorry, we don't have the capacity to test the workaround now, and the original issue is till happening on my machine and should be addressed without workarounds.

ChetanSharma-msft commented 2 years ago

@smauglys - We will check the status of it internally and let you know.

jackblackCH commented 2 years ago

Similar issue here: Created a teams tab. getContext callback does not work on localhost but works if hosted.

HunaidHanfee-MSFT commented 2 years ago

Can you try microsoftTeams.initialize to move it to when the page gets load? in authenticate popup before calling getContext?

HunaidHanfee-MSFT commented 2 years ago

Hello All, We have deployed an app where we have implemented this functionality. Please download this manifest and try in your tenant. Auth_Context_test.zip

When you will add the tab in Teams team, configure page will see two buttons image image

Please select Set signin then click on save (if you just want to check getContext you can click on Check getContext button as well). Now, once the tab is open you will see a button image image

here the code that will execute when you click on it-

microsoftTeams.initialize();
        console.log("SignIn start")
        microsoftTeams.authentication.authenticate({
            url: window.location.origin + "/signin-simple-start",
            successCallback: () => {
                history.push("/navigateDomain");
            },
            failureCallback: (reason) => {
                alert(reason);
                history.push("/errorpage");
            }
});

Once you are succesfully signed in - We have added two button in the last authenticate step, one to getContext and alert the current tenant Id and other to call notifySuccess image

code that is written at end of the step -

useEffect(() => {
        microsoftTeams.initialize();
        const hashParams: any = getHashParameters();
        if (hashParams["error"]) {
            // Authentication/authorization failed
            alert("notifyFailure gets called -- " + hashParams["error"]);
            microsoftTeams.authentication.notifyFailure(hashParams["error"]);
        } else if (hashParams["id_token"]) {
            // Success
            if (hashParams["access_token"]) {
                localStorage.setItem("auth.result", JSON.stringify({
                    accessToken: hashParams["access_token"]
                }));
            }

        } else {
            // Unexpected condition: hash does not contain error or access_token parameter            
            alert("notifyFailure gets called -- Unknown error ");
            microsoftTeams.authentication.notifyFailure("UnexpectedFailure");
        }
    }, [props.location]);

    const callContext = () => {
        microsoftTeams.initialize(() => {
            microsoftTeams.getContext(context => {
                alert(context.tid);
            })
        })
    }

    const callNotifySuccess = () => {
        alert("notifySuccess gets called");
        microsoftTeams.authentication.notifySuccess("TEST");
    }

    return (
        <>
            <div>
                <Text content="Click on it to call getContext and see current tenant Id." />
                <div><Button content="Call getContext" onClick={() => { callContext() }} /></div>
            </div>
            <div>
                <Text content="Call notifySuccess." />
                <div><Button content="Call notifySuccess" onClick={() => { callNotifySuccess() }} /></div>
            </div>
        </>
    );

Click on notifySuccess to close the popup and redirect to page. Once you are redirected there again we have a button that will alert context.theme

Please try it at your end and let us know if you facing this issue with our app as well.

Thanks

malsabbagh commented 2 years ago

@HunaidHanfee-MSFT

It is not reproducible everywhere only certain machines have this issue. This is the app you provided as you can see the issue is still reproducible with Microsoft Teams Version 1.4.00.35564. image

Meghana-MSFT commented 2 years ago

Could you please share the console logs from Desktop app? Please follow this to get the logs - https://docs.microsoft.com/en-us/microsoftteams/platform/tabs/how-to/developer-tools

malsabbagh commented 2 years ago

@Meghana-MSFT where should I send the logs? I can't upload here due privacy reasons.

ChetanSharma-msft commented 2 years ago

Could you please share only relevant logs information, so that we can check on it.

Meghana-MSFT commented 2 years ago

@malsabbagh - Please share the logs at microsoftteamsdev@microsoft.com