Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MS Teams Desktop tabs getAuthToken() flashes popup every time #1994

Open
jurisjansons opened this issue Oct 17, 2023 · 18 comments
Open

MS Teams Desktop tabs getAuthToken() flashes popup every time #1994

jurisjansons opened this issue Oct 17, 2023 · 18 comments
Assignees
Labels
needs author feedback teams issue issue that has been reviewed and likely teams specific teams-developer-support

Comments

@jurisjansons
Copy link

There is an issue with authentication.getAuthToken().then(...). When called, it opens popup every time when opening tab or switching tabs that causes an interuption for users. If I open Teams from web, no popup is shown and token is retreived from cache in matter of milliseconds. Using newest version "@microsoft/teams-js": "^2.16.0".

@ChetanSharma-msft
Copy link

Hello @jurisjansons - Thanks for raising your query.
Please let us know whether you are trying it in classic teams or Teams 2.1?

@jurisjansons
Copy link
Author

@ChetanSharma-msft Classic Teams, in New Teams everything is working fine actually

@Nivedipa-MSFT
Copy link

@jurisjansons - We will test this in Classic Teams and update you soon.

@SaiPratap-MSFT
Copy link

SaiPratap-MSFT commented Oct 22, 2023

@jurisjansons - We have tested this in Classic Teams with "@microsoft/teams-js": "^2.16.0". We didnt find any issue. Here is the video reference attaching. Could you please test this once and Confrim

authTokenMethod.mp4

@jurisjansons
Copy link
Author

jurisjansons commented Oct 23, 2023

This is what I get. Tabs are React SPA project, seperate from Bot. In video, you can see background turning little yellow, that means teams.js is initialized. Might not be related to getAuthToken, will investigate further

Microsoft.Teams.Classic.2023-10-23.14-03-02.mp4

Code used to get token:
useEffect(() => { authentication .getAuthToken() .then((token) => { app.getContext().then((context) => { axios .get<IChannelsResponse>("channels/getUserChannels", { headers: { Authorization: 'Bearer ${token}', }, params: { userObjectId: context.user?.id }, }) .then((res) => { setChannels(res.data.channels); setIsChannelsLoading(false); }) .catch((err) => { setIsChannelsLoading(false); console.log("err:", err); }); }); }) .catch((err) => { setIsChannelsLoading(false); console.log("err:", err); }); }, []);

@SaiPratap-MSFT
Copy link

@jurisjansons - Could you please confirm if your issue has resolved or still investigating

@jurisjansons
Copy link
Author

@SaiPratap-MSFT issue still persists

@SaiPratap-MSFT
Copy link

SaiPratap-MSFT commented Nov 16, 2023

@jurisjansons - Did you get any error log or console log, please share with us show that we can investigate from our end.

@jurisjansons
Copy link
Author

@SaiPratap-MSFT Only error I get is from await credential.getToken(scopes) which is causing delay around 5s on my machine and it throws ErrorWithCode.UiRequiredError: Failed to get access token cache silently, please login first: you need login first before get access token.. After getting error I call await credential.login(scopes), (getting response around 1s) which is what causes to login popup show up every time switching tabs

@SaiPratap-MSFT
Copy link

@jurisjansons - We will check this and update you soon.

@ChetanSharma-msft
Copy link

ChetanSharma-msft commented Dec 1, 2023

Hello @jurisjansons - You need to call the login(...) function when you get the UiRequiredError. You can also leverage the @microsoft/teamsfx-react package when building react app, which handles the login for you.

Please refer this thread as well: OfficeDev/teams-toolkit#10379

You can also refer this sample: https://github.com/OfficeDev/Microsoft-Teams-Samples/blob/main/samples/meetings-sidepanel/nodejs/server/Controllers/HomeController.js

Sample repo: https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples

@jurisjansons
Copy link
Author

@ChetanSharma-msft That is exactly what I am doing. The issue is that getToken() always fails with UiRequiredError and is causing very long delay before it returns response or rather throws error. For me its ~5 seconds, some users are experiencing ~20s delay, before popup flashes (error is thrown and login() is called).

Only Teams Desktop (old version) is affected.
New Teams and Teams Web is working fine, no delays on initial tab open when getToken() throws UiRequiredError and popup opens for sign in and all the subsequent tab opens will not get UiRequiredError because getToken() will be successfully resolved.

Code that is causing this delay and throws error every time tab is opened:

import { ProviderState, Providers } from "@microsoft/mgt-element"; //@^3.1.3
import { TeamsFxProvider } from "@microsoft/mgt-teamsfx-provider"; //@^3.1.3
import { TeamsUserCredential } from "@microsoft/teamsfx"; //@^2.3.0

...

const scopes = ["User.Read", "User.ReadBasic.All"];

const credential = new TeamsUserCredential({
  clientId: `${process.env.REACT_APP_CLIENT_ID}`,
  initiateLoginEndpoint: "/auth-start.html",
});

Providers.globalProvider = new TeamsFxProvider(credential, scopes);

export default function App() {

...

    const initialize = async () => {
        try {
            await credential.getToken(scopes); //Causing delay 5-30s and always throws error on Teams Desktop
            Providers.globalProvider.setState(ProviderState.SignedIn);
        } catch (error) {
            await credential.login(scopes);
            Providers.globalProvider.setState(ProviderState.SignedIn);
        }
            
        setInitialized(true);
    };

...

}

@ChetanSharma-msft
Copy link

Hello @jurisjansons - Thanks for sharing the information.
We have informed engineering team and let you know the updates, if any.

@jurisjansons
Copy link
Author

@ChetanSharma-msft Hi! Are there any updates on this matter?

@Prasad-MSFT
Copy link

@jurisjansons - Could you please refer this thread and let us know if that helps?
OfficeDev/teams-toolkit#10379

@jekloudaMSFT jekloudaMSFT added the teams issue issue that has been reviewed and likely teams specific label Mar 26, 2024
@jurisjansons
Copy link
Author

@Prasad-MSFT Seems like original issue is resolved updating all libraries and using authentication as shown in example from your provided thread. Used sample code for authentication from this: https://github.com/KennethBWSong/authCodeTemplate/tree/master

But unfortunately, I'm now facing different issue and can't seem to find any examples on how to use @microsoft/mgt-react with @microsoft/mgt-teamsfx-provider library with provided example. Could you share some examples? I'm currently getting 401 error, when loading Person component.

const scopes = ["User.Read", "User.ReadBasic.All"];

export default function App() {
  const { i18n } = useTranslation();

  const { loading, theme, themeString, teamsUserCredential } =
    useTeamsUserCredential({
      initiateLoginEndpoint: "/auth-start.html",
      clientId: `${process.env.REACT_APP_CLIENT_ID}`,
    });

  const initialize = useCallback(async () => {
    if (loading || !teamsUserCredential) {
      return;
    }

    await app.initialize();

    await init(process.env.REACT_APP_AMPLITUDE_API_KEY as string).promise;

    const provider = new TeamsFxProvider(teamsUserCredential, scopes);
    Providers.globalProvider = provider;

    try {
      await teamsUserCredential.getToken(scopes);
      Providers.globalProvider.setState(ProviderState.SignedIn);
    } catch (error) {
      await teamsUserCredential.login(scopes).catch((error) => {
        console.error(error);
      });
      Providers.globalProvider.setState(ProviderState.SignedIn);
    }

    app.getContext().then((context) => {
      setUserId(context.user?.id);

      const language = context.app.locale.split("-")[0];
      i18n.changeLanguage(language);
      moment.locale(context.app.locale);

      app.notifySuccess();
    });
  }, [i18n, loading, teamsUserCredential]);

  useEffect(() => {
    initialize();
  }, [initialize]);

...

Logs from console:

[Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Info - Create teams user credential
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Verbose - Validate authentication configuration
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Info - Get access token with scopes: User.Read User.ReadBasic.All
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Verbose - Get SSO token from memory cache
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Verbose - Failed to call acquireTokenSilent. Reason: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.  For more visit: aka.ms/msaljs/browser-errors. 
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Verbose - Failed to call ssoSilent. Reason: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.  For more visit: aka.ms/msaljs/browser-errors. 
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Error - Failed to get access token cache silently, please login first: you need login first before get access token.
App.tsx:80 [Wed, 27 Mar 2024 12:11:38 GMT] : @microsoft/teamsfx : Info - Popup login page to get user's access token with scopes: User.Read User.ReadBasic.All
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:39 GMT] : @microsoft/teamsfx : Error - Consent failed for the scope User.Read User.ReadBasic.All with error: Get empty response.
[Wed, 27 Mar 2024 12:11:40 GMT] : @microsoft/teamsfx : Verbose - Get SSO token from memory cache
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:40 GMT] : @microsoft/teamsfx : Info - Get access token with scopes: User.Read User.ReadBasic.All
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:40 GMT] : @microsoft/teamsfx : Verbose - Failed to call acquireTokenSilent. Reason: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.  For more visit: aka.ms/msaljs/browser-errors. 
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:40 GMT] : @microsoft/teamsfx : Verbose - Failed to call ssoSilent. Reason: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.  For more visit: aka.ms/msaljs/browser-errors. 
useTeamsUserCredential.js:22 [Wed, 27 Mar 2024 12:11:40 GMT] : @microsoft/teamsfx : Error - Failed to get access token cache silently, please login first: you need login first before get access token.

@jurisjansons
Copy link
Author

@Prasad-MSFT unfortunately the issue is back on MS Teams Web App and MS Teams Desktop App. Switching tabs, flashes login popup on every switch because of this error in console: Cannot get access token due to error: n.UiRequiredError: Failed to get access token cache silently, please login first: you need login first before get access token.

Package versions:
app:

"@microsoft/teams-js": "^2.21.0",
"@microsoft/teamsfx": "^2.3.0",
"@microsoft/teamsfx-react": "^3.1.1",

auth-start.html:

https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js
https://alcdn.msauth.net/browser/2.35.0/js/msal-browser.min.js

auth-sso.html:

https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js
https://unpkg.com/@microsoft/mgt@3/dist/bundle/mgt-loader.js

auth-end.html:

https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js
https://alcdn.msauth.net/browser/2.35.0/js/msal-browser.min.js

@Prasad-MSFT
Copy link

Prasad-MSFT commented May 27, 2024

@jurisjansons - Is it occurring in New Teams??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs author feedback teams issue issue that has been reviewed and likely teams specific teams-developer-support
Projects
None yet
Development

No branches or pull requests

7 participants