Search code examples
microsoft-teamsteams-toolkitmicrosoft-teams-js

[email protected] TeamsUserCredential.getToken results in login required error


I'm creating a Teams Static web application to be used in teams.

The error I am getting when trying to get the Teams a teams access token is as follows:

Failed to get access token cache silently, please login first: you need login first before get access token

Code that has the error:

const { 
  loading,
  theme,
  themeString,
  teamsUserCredential
} = useTeamsUserCredential({
        initiateLoginEndpoint: `${process.env.REACT_APP_INITIATE_LOGIN_ENDPOINT}/auth-start.html`,
        clientId: process.env.REACT_APP_AAD_APP_CLIENT_ID as string
    });
 
// calling getToken
const scopes = [
        "openid",
        "profile",
        process.env.REACT_APP_API_SCOPE as string,
    ];
 
// Throws the "please login first" error 

const token = await teamsUserCredential?.getToken(scopes)

The issue is only occurring on "New Teams" for Mac. The same code works on "New Teams" on Windows.

To get around the issue I have added code to allow the user to login:

teamsUserCredential.login(scopes)

Logging in solves the issue temporarily, however if I close teams and open it again users are forced to login again.

Business requirement was to put the application into Teams so that users did not have to login.

---------------- UPDATE -------------

Using a sample project from microsoft I tried the following and it still failed:

const apiClient = createApiClient( 
  ${baseUrl}/,
  new BearerTokenAuthProvider(async () => (await credential!.getToken(scopes))!.token) 
) 

apiClient.get('accounts').then((response: any) => { 
  return response.data; })
.catch((err: any) => { trackException(err); });


Solution

  • The issue was related to the @azure/msal-browser package.

    The auth-start.html and auth-end.html used a different msal-browser version than my application was using. The sessionStorage cache was not compatible between the different versions.

    My auth-start.html and auth-end.html files referenced msal-browser 2.21.0 using a cdn reference.

    The @microsoft/teamsfx package.json used msal-browser: "^2.21.0" this led to a msal-browser version "2.37.1" being installed.

    The cache created with version 2.21.0 was not compatible with 2.37.1.

    I upgraded my CDN reference to a more recent msal-browser version and it works!!