OfficeDev / TeamsFx

Developer tools for building Teams apps
Other
427 stars 165 forks source link

Neither SSO nor login() works on iOS for tab app #9920

Closed juxnpxblo closed 5 months ago

juxnpxblo commented 8 months ago

Describe the bug On my Teams personal tab React app running on web, once the library has loaded, I can successfully getToken(), but the same does not happen on iOS. Even after logging in successfully, getToken() persists to fail.

To Reproduce Load a React app on a personal tab on iOS:

import { useTeamsUserCredential } from "@microsoft/teamsfx-react"
import type { TeamsUserCredentialAuthConfig } from "@microsoft/teamsfx";

const authConfig: TeamsUserCredentialAuthConfig = {
  clientId: "<clientId>",
  initiateLoginEndpoint: window.location.origin + "/auth-start.html",
};

function App() {
  const { teamsUserCredential } = useTeamsUserCredential(authConfig);

  useEffect(() => {
    if(!teamsUserCredential) {
      return
    }

    // If I were to getToken() here, it would fail on iOS, so let's try to login first

    console.log("valid teamsUserCredentials:", teamsUserCredential)
    console.log("trying to perform login...")

    teamsUserCredential.login("User.Read")
      .then(() => {
        console.log("login was successful")
        console.log("trying to get token...")

        teamsUserCredential.getToken("User.Read")
          .then((token) => {
            console.log("token acquired:", token)
          })
          .catch((err) => {
            console.error("token acquisition failed.", err)
          })})
    .catch(err => {
      console.error("login failed.", err)
    })
  }, [teamsUserCredential])

  return null;
}

Expected behavior SSO or login() should work.

Logs » [Fri, 01 Sep 2023 20:30:00 GMT] : @microsoft/teamsfx : Verbose - Validate authentication configuration » [Fri, 01 Sep 2023 20:30:00 GMT] : @microsoft/teamsfx : Info - Create teams user credential » "valid teamsUserCredentials:" {"config":{"clientId":"","initiateLoginEndpoint":"https://myappurl.com/auth-start.html"},"ssoToken":null,"initialized":false} » trying to perform login... » [Fri, 01 Sep 2023 20:30:00 GMT] : @microsoft/teamsfx : Info - Popup login page to get user's access token with scopes: User.Read » login was successful » trying to get token... » [Fri, 01 Sep 2023 20:30:01 GMT] : @microsoft/teamsfx : Info - Get access token with scopes: User.Read » [Fri, 01 Sep 2023 20:30:01 GMT] : @microsoft/teamsfx : Verbose - Get SSO token from memory cache » [Fri, 01 Sep 2023 20:30:01 GMT] : @microsoft/teamsfx : Verbose - Failed to call acquireTokenSilent. Reason: no_account_error: No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.. » [Fri, 01 Sep 2023 20:30:02 GMT] : @microsoft/teamsfx : Verbose - Failed to call ssoSilent. Reason: login_required: AADSTS50058: A silent sign-in request was sent but no user is signed in. The cookies used to represent the user's session were not sent in the request to Azure AD. This can happen if the user is using Internet Explorer or Edge, and the web app sending the silent sign-in request is in different IE security zone than the Azure AD endpoint (login.microsoftonline.com). Trace ID: 2c72129a-d429-4045-964b-3ef23aa80200 Correlation ID: 67d26e3f-510d-4767-9735-40c010b24900 Timestamp: 2023-09-01 20:30:02Z. » [Fri, 01 Sep 2023 20:30:02 GMT] : @microsoft/teamsfx : Error - Failed to get access token cache silently, please login first: you need login first before get access token. » "token acquisition failed." {"name":"_ErrorWithCode.UiRequiredError","code":"UiRequiredError"}

microsoft-github-policy-service[bot] commented 8 months ago

Thank you for contacting us! Any issue or feedback from you is quite important to us. We will do our best to fully respond to your issue as soon as possible. Sometimes additional investigations may be needed, we will usually get back to you within 2 days by adding comments to this issue. Please stay tuned.

KennethBWSong commented 8 months ago

Hi @juxnpxblo Thank you for using our Toolkit. There is known issue on mobile platforms(IOS, Android) that ssoSilent in Auth Code Flow does not work and only manually login works. You can try OBO Flow to get tokens like this sample.

jlammers0 commented 7 months ago

Hello @KennethBWSong. Is there a timeline for when ssoSilent on mobile platforms will be fixed/supported?

KennethBWSong commented 7 months ago

@jlammers0 Sorry we don't have info on this. You can try to raise an issue here. We will also track the status and let you know when this issue is fixed.

civlon commented 6 months ago

Hi @KennethBWSong is there a new update on this? I have some question regarding this issue. First do we know why there are problems for mobile iOS logins, so that we could potentially build a workaround for this problem? Could it be that the login popup/redirect simply gets blocked by iOS? If so do you have an idea how we can allow this popup to show on the teams app? Also i have troubles understanding your suggested solution. To use the OBO Flow we need an already authenticated user, right? So if the login does not work how am i supposed to use this flow. I don't really understand the sample, because for me it seems like they are still using the normal SSO to authenticate users. You said only manually login works, are you talking about login via msal-react? If so do you have an example which shows how this manual login is implemented so it works for iOS mobile. Thanks for your help.

KennethBWSong commented 6 months ago

@civlon Sorry for late reply. This bug is caused by IOS client, and we have created an upstream ticket for tracking this issue. We will let you know as soon as we have any updates.

karlrez commented 6 months ago

Hi @KennethBWSong is there a new update on this? I have some question regarding this issue. First do we know why there are problems for mobile iOS logins, so that we could potentially build a workaround for this problem? Could it be that the login popup/redirect simply gets blocked by iOS? If so do you have an idea how we can allow this popup to show on the teams app? Also i have troubles understanding your suggested solution. To use the OBO Flow we need an already authenticated user, right? So if the login does not work how am i supposed to use this flow. I don't really understand the sample, because for me it seems like they are still using the normal SSO to authenticate users. You said only manually login works, are you talking about login via msal-react? If so do you have an example which shows how this manual login is implemented so it works for iOS mobile. Thanks for your help.

@civlon My current workaround is to log in with useGraphWithCredential() and then calling getToken() works after.

import { useTeamsUserCredential, useGraphWithCredential } from "@microsoft/teamsfx-react"
import type { TeamsUserCredentialAuthConfig } from "@microsoft/teamsfx";
import { TeamsFxProvider } from '@microsoft/mgt-teamsfx-provider';
import { Providers, ProviderState } from '@microsoft/mgt-element';

const authConfig: TeamsUserCredentialAuthConfig = {
  clientId: "<clientId>",
  initiateLoginEndpoint: window.location.origin + "/auth-start.html",
};

function App() {
  const { teamsUserCredential } = useTeamsUserCredential(authConfig);

  const {
    error,
    reload,
  } = useGraphWithCredential(
    async (graph, teamsUserCredential, scope) => {
     // on ios graph sign in fails initially
     // requires manually calling reload() to sign in and then try get token again after

     const profile = await graph.api("/me").get();

      // Initialize Graph Toolkit TeamsFx provider
      const provider = new TeamsFxProvider(teamsUserCredential, scope);
      Providers.globalProvider = provider;
      Providers.globalProvider.setState(ProviderState.SignedIn);

      if (!error) setGraphApiAuthenticated(true);
    },

    { scope: ["User.Read"], credential: teamsUserCredential }
  );

useEffect(() => {
    if(!teamsUserCredential) {
      return
    }

   teamsUserCredential.getToken("User.Read")
     .then((token) => {
       console.log("token acquired:", token)
     }).catch((err) => {
      console.error("token acquisition failed.", err)
     })
  }, [teamsUserCredential, graphApiAuthenticated])

  return null;
}
<button onClick={reload}>Authorise App</button>

package.json

"@microsoft/mgt-teamsfx-provider": "^3.0.1",
"@microsoft/mgt-element": "^2.8.0",
"@microsoft/teamsfx": "^2.2.2",
"@microsoft/teamsfx-react": "^3.0.1",
KennethBWSong commented 6 months ago

@karlrez Thanks for your workaround! We will keep tracking this issue and let you know when we have any update.

shabbir-dhangot commented 6 months ago

@karlrez @KennethBWSong I am facing similar issue in New Teams Desktop Client. Below is errorI am facing. I tried solution you gave but not working for me. Is there Anything I am missing.

GraphErrorHandler.ts:44  Uncaught (in promise) r.UiRequiredError: Failed to get access token cache silently, please login 
first: you need login first before get access token.
at e.<anonymous> (teamsUserCredential.browser.ts:266:15)
at d (regeneratorRuntime.js:45:16)
at Generator.<anonymous> (regeneratorRuntime.js:133:17)
at Generator.throw (regeneratorRuntime.js:74:21)
at sC (asyncToGenerator.js:3:20)
KennethBWSong commented 5 months ago

@shabbir-dhangot This error will occur when application requires user login explicitly in order to acquire the token, and thus you can trigger teamsUserCredential.login() when you get the error in most scenario. If you have manually login, would you please share your logic to login?

kristofferarn commented 5 months ago

Is there any news on this iOS issue? We have customers that are unable to use our apps on mobile devices so any feedback would be appreciated. I had no success in trying the workaround commented above.

ThomasPe commented 5 months ago

Can confirm the workaround isn't working for me either.

KennethBWSong commented 5 months ago

@kristofferarn @ThomasPe Thanks for reporting. We still don't have any update from Teams mobile team, and would suggest you to use OBO flow for authentication. You can refer to the sample here.

mr-github-user commented 5 months ago

@shabbir-dhangot This error will occur when application requires user login explicitly in order to acquire the token, and thus you can trigger teamsUserCredential.login() when you get the error in most scenario. If you have manually login, would you please share your logic to login?

I am using teamsUserCredential to try and obtain an accessToken for an api I manage.

After calling await teamsUserCredential.getToken(scopes) I get the following error:

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

I then call await teamsUserCredential.login(scopes) the user is able to login successfully and no error is encountered.

After login I call await teamsUserCredential.getToken(scopes) which results in the same error as before:

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

This issue is only happening to users that are using Teams on iphone. And calls to teamsUserCredentials.getUserInfo() work.

Are there any updates or workarounds?

mr-github-user commented 5 months ago

@civlon Sorry for late reply. This bug is caused by IOS client, and we have created an upstream ticket for tracking this issue. We will let you know as soon as we have any updates.

Is there any update on this ticket? Are we able to follow it's progress somewhere else?

ThomasPe commented 3 months ago

@KennethBWSong any news on this?

KennethBWSong commented 3 months ago

@ThomasPe Thank you for using our Toolkit. Please refer to this issue: https://github.com/OfficeDev/TeamsFx/issues/7574.

mr-github-user commented 3 months ago

The issue I was dealing with was related to msal-browser version conflict. The session storage cache was not compatible with my app.

see issue: #10379 for more details.

ThomasPe commented 3 months ago

that was it! thx @mr-github-user!

petr-istratov commented 1 month ago

Still having this issue. updating msal browser didn't help. @KennethBWSong I've deployed clean sample from https://github.com/OfficeDev/TeamsFx-Samples/tree/dev/hello-world-tab-with-backend and it still doesn't work on Outlook mobile