microsoft-graph-toolkit icon indicating copy to clipboard operation
microsoft-graph-toolkit copied to clipboard

[BUG] mgt-teamsfx-provider failing to authenticate

Open seiggy opened this issue 1 year ago • 15 comments

Describe the bug Following the tutorial from the MS Documentation on how to use Graph Toolkit with Teams Tab applications. After authorizing the app, the code throws errors in the console and nothing is displayed:

[Fri, 12 Apr 2024 22:20:22 GMT] : @microsoft/teamsfx : Verbose - Get SSO token from memory cache
useTeamsUserCredential.js:22 [Fri, 12 Apr 2024 22:20:22 GMT] : @microsoft/teamsfx : Info - Get access token with scopes: User.Read Calendars.Read
useTeamsUserCredential.js:22 [Fri, 12 Apr 2024 22:20:22 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 [Fri, 12 Apr 2024 22:20:22 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 [Fri, 12 Apr 2024 22:20:22 GMT] : @microsoft/teamsfx : Error - Failed to get access token cache silently, please login first: you need login first before get access token.
TeamsFxProvider.ts:136  🦒: Cannot get access token due to error: ErrorWithCode.UiRequiredError: Failed to get access token cache silently, please login first: you need login first before get access token.
(anonymous) @ TeamsFxProvider.ts:136
rejected @ TeamsFxProvider.ts:1
Promise.then (async)
step @ TeamsFxProvider.ts:1
(anonymous) @ TeamsFxProvider.ts:1
__awaiter @ TeamsFxProvider.ts:1
getAccessToken @ TeamsFxProvider.ts:126
(anonymous) @ AuthenticationHandler.ts:79
(anonymous) @ tslib.es6.mjs:121
__awaiter @ tslib.es6.mjs:117
execute @ AuthenticationHandler.ts:63
(anonymous) @ HTTPClient.ts:88
(anonymous) @ tslib.es6.mjs:121
__awaiter @ tslib.es6.mjs:117
sendRequest @ HTTPClient.ts:81
(anonymous) @ GraphRequest.ts:372
(anonymous) @ tslib.es6.mjs:121
__awaiter @ tslib.es6.mjs:117
send @ GraphRequest.ts:366
(anonymous) @ GraphRequest.ts:661
(anonymous) @ tslib.es6.mjs:121
__awaiter @ tslib.es6.mjs:117
post @ GraphRequest.ts:647
(anonymous) @ Batch.ts:115
fulfilled @ Batch.ts:1
Promise.then (async)
step @ Batch.ts:1
(anonymous) @ Batch.ts:1
__awaiter @ Batch.ts:1
executeNext @ Batch.ts:84
(anonymous) @ Batch.ts:165
(anonymous) @ Batch.ts:1
__awaiter @ Batch.ts:1
executeAll @ Batch.ts:161
(anonymous) @ graph.userWithPhoto.ts:119
fulfilled @ graph.userWithPhoto.ts:1
Promise.then (async)
step @ graph.userWithPhoto.ts:1
fulfilled @ graph.userWithPhoto.ts:1
Promise.then (async)
step @ graph.userWithPhoto.ts:1
(anonymous) @ graph.userWithPhoto.ts:1
__awaiter @ graph.userWithPhoto.ts:1
getUserWithPhoto @ graph.userWithPhoto.ts:33
(anonymous) @ mgt-person.ts:1167
(anonymous) @ mgt-person.ts:1
__awaiter @ mgt-person.ts:1
loadState @ mgt-person.ts:1116
task @ baseTaskComponent.ts:212
run @ task.ts:348
_performTask @ task.ts:300
hostUpdate @ task.ts:261
(anonymous) @ reactive-element.ts:1440
performUpdate @ reactive-element.ts:1440
scheduleUpdate @ reactive-element.ts:1338
__enqueueUpdate @ reactive-element.ts:1310
await in __enqueueUpdate (async)
requestUpdate @ reactive-element.ts:1268
__initialize @ reactive-element.ts:1017
ReactiveElement @ reactive-element.ts:1000
LitElement @ lit-element.ts:122
MgtBaseTaskComponent @ baseTaskComponent.ts:96
MgtTemplatedTaskComponent @ templatedTaskComponent.ts:59
MgtPerson @ mgt-person.ts:511
createElement @ react-dom.development.js:9784
createInstance @ react-dom.development.js:10941
completeWork @ react-dom.development.js:22187
completeUnitOfWork @ react-dom.development.js:26596
performUnitOfWork @ react-dom.development.js:26568
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Show 70 more frames
Show less
graph.microsoft.com/v1.0/me/calendarview?$orderby=start/dateTime&startdatetime=2024-04-12T22:20:21.548Z&enddatetime=2024-04-15T22:20:21.548Z:1 
        
        
        Failed to load resource: the server responded with a status of 401 ()

To Reproduce Steps to reproduce the behavior:

  1. Follow guide: https://learn.microsoft.com/en-us/graph/toolkit/get-started/build-a-microsoft-teams-tab#build-a-new-teams-tab-using-react-and-fluent-ui-with-the-teams-toolkit
  2. Run app 3!-- if possible, please link to a GitHub project that reproduces the issue --> Issue reproduced here: https://github.com/seiggy/TeamsFxDebug

Expected behavior The user's calendar should show up using the <Agenda> component.

Screenshots If applicable, add screenshots to help explain your problem. image

Environment (please complete the following information):

  • OS: Windows 11
  • Browser Edge
  • Framework React
  • Context Microsoft Teams, Office Add-ins
  • Version [e.g. 0.1]
  • Provider TeamsFxProvider (config in linked repo)

seiggy avatar Apr 12 '24 22:04 seiggy

@SLdragon This looks to be an issue in the TeamsFxProvider

gavinbarron avatar Apr 15 '24 15:04 gavinbarron

Encountered the same issue in my project. Had another project that worked so tried to compare the two. Seems like @microsoft/teamsfx-react version 3.1.1 was the issue on my end. Hard downgraded it to 3.1.0 and the issue went away.

Current dependencies: "@microsoft/mgt-element": "^4.2.1", "@microsoft/mgt-teamsfx-provider": "^4.2.1", "@microsoft/teams-js": "^2.20.0", "@microsoft/teamsfx": "^2.3.1", "@microsoft/teamsfx-react": "3.1.0",

kristofferarn avatar Apr 25 '24 12:04 kristofferarn

Had to downgrade the following dependencies according to your GitHub repo as well compared to the fluent-ui-tab-sample:

    "@microsoft/teams-js": "2.13.0",
    "@microsoft/teamsfx": "2.2.0",
    "@microsoft/teamsfx-react": "3.0.0",

ThomasPe avatar May 07 '24 20:05 ThomasPe

Had to downgrade the following dependencies according to your GitHub repo as well compared to the fluent-ui-tab-sample:

    "@microsoft/teams-js": "2.13.0",
    "@microsoft/teamsfx": "2.2.0",
    "@microsoft/teamsfx-react": "3.0.0",

Yep. This downgrade (along with a bunch of other changes for my actual application) fixed my issue. Definitely an issue with the teamsfx packages.

seiggy avatar Jul 12 '24 19:07 seiggy

The aforementioned packages have been updated recently. Do the new version cause the same issue? @seiggy @ThomasPe @kristofferarn

musale avatar Jul 16 '24 07:07 musale

Had to downgrade the following dependencies according to your GitHub repo as well compared to the fluent-ui-tab-sample:

    "@microsoft/teams-js": "2.13.0",
    "@microsoft/teamsfx": "2.2.0",
    "@microsoft/teamsfx-react": "3.0.0",

Yep. This downgrade (along with a bunch of other changes for my actual application) fixed my issue. Definitely an issue with the teamsfx packages.

care to share your solution for the issue? i'm struggling with this same thing. I've changed the deps following this thread and don't see the error anymore on the console but the components render empy 🥲

dario-pairup avatar Jul 16 '24 14:07 dario-pairup

@musale, upgrading the packages to the latest version gives me the following error: image

kristofferarn avatar Jul 17 '24 08:07 kristofferarn

@kristofferarn allow me to repro this and get back to you.

musale avatar Jul 17 '24 08:07 musale

@musale did you get a chance to repro?

Would be nice if you could also check the teamsfx login and token logic with an external guest using iOS. We're having problems with this on all of our apps. Can raise a new issue if needed.

kristofferarn avatar Aug 01 '24 08:08 kristofferarn

care to share your solution for the issue? i'm struggling with this same thing. I've changed the deps following this thread and don't see the error anymore on the console but the components render empy 🥲

@dario-pairup - So beyond the package changes here, because I was trying to write my React app to support running both in Teams and in the browser with SSO for both, the major change I made was splitting that out into two separate components instead of trying to use a single component to detect and load the correct provider. Now if the user comes from teams, I use a completely different host component I wrote that uses the <TeamsFxContext.Provider>, where my web host now uses my custom <AppContext.Provider> with MSAL.

The Teams App host is pretty simple:

export default function TeamsAppHost() {
    const { loading, theme, themeString, teamsUserCredential } = useTeamsUserCredential({
      initiateLoginEndpoint: config.initiateLoginEndpoint!,
      clientId: config.clientId!
    });
    
    useEffect(() => {
      const provider = new TeamsFxProvider(teamsUserCredential!, scopes);
      Providers.globalProvider = provider;
    }, [teamsUserCredential]);
    
    const [state, setState] = useState({
      searchTerm: '*',
      sidebar: {
        isMinimized: false
      },
      token: '',
      theme: { key: 'default', fluentTheme: teamsLightTheme },
      selectedTab: '',
      breadcrumbs: ["None"] as BreadcrumbNavItem[]
    });

    return (
        <TeamsFxContext.Provider value={{ theme, themeString, teamsUserCredential }}>
          <FluentProvider
            theme={
              themeString === 'dark'
              ? teamsDarkTheme
              : themeString === 'contrast'
              ? teamsHighContrastTheme
              : {
                ...teamsLightTheme,
                colorNeutralBackground3: "#eeeeee",
              }
            }
            style={{ background: tokens.colorNeutralBackground3 }}
            >
              <AppContext.Provider value={{ state, setState }}>
                {loading ? (
                  <Spinner style={{ margin: 100 }} />
                ) : (
                  <TeamsTab />
                )}
              </AppContext.Provider>
            </FluentProvider>
        </TeamsFxContext.Provider>
    )
}

I'm pretty new to React, so this is likely not anywhere near great code 🤣

seiggy avatar Aug 02 '24 12:08 seiggy

@kristofferarn not yet :/ I've been engaged in another project so I'm getting back to MGT from this week. A little bit of backlog but I'll try my best to repro this week!

musale avatar Aug 05 '24 12:08 musale