Search code examples
microsoft-graph-apimicrosoft-teamsazure-ad-msalmicrosoft-graph-teamsteams-toolkit

"OnBehalfOfUserCredential" in teamsfx is not supported in browser


We are working on adding SSO for Tab App and following the below documentation: https://learn.microsoft.com/en-us/microsoftteams/platform/tabs/how-to/authentication/tab-sso-graph-api?tabs=nodejs#configure-code-to-fetch-access-token-using-msal

We need to pass the access token received from OBO flow to Graph API. Currently we are using createMicrosoftGraphClient from teamsfx to make Graph API calls. On searching through teamsfx documentation for functions that can be used to pass sso token to Graph API, I came across OnBehalfOfUserCredential. However when use this to pass sso token and make Graph API calls. I see the below error when I run Teams App in browser: onBehalfOfUserCredential.browser.ts:26 Uncaught ErrorWithCode.RuntimeNotSupported: OnBehalfOfUserCredential is not supported in browser.

Are there any alternatives to this in teamsfx which will work in both browser and desktop client Or any other workarounds on How can I pass sso token to Graph Api ?


Solution

  • Naina, OnBehalfOfUserCredential only works in Node JS environment, because it designed to running in backend service and it required client secret or certificate, which cannot exposed in browser environment.

    For your scenario, we have a sample to demonstrate how to use OnBehalfOfUserCredential for Teams Tab App with backend service:

    https://github.com/OfficeDev/TeamsFx-Samples/tree/dev/hello-world-tab-with-backend

    And in backend Azure Function, it uses OnBehalfOfUserCredential to call graph API and send back to Teams App:

    https://github.com/OfficeDev/TeamsFx-Samples/blob/dev/hello-world-tab-with-backend/api/getUserProfile/index.ts#L65

    Below is the code snippet in backend service and please use TeamsFx SDK >= 2.0.0:

      const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
        authorityHost: process.env.M365_AUTHORITY_HOST,
        clientId: process.env.M365_CLIENT_ID,
        tenantId: process.env.M365_TENANT_ID,
        clientSecret: process.env.M365_CLIENT_SECRET,
      };
       
      // sso token is obtained from request sent by Teams App
      const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
      const graphClient: Client = createMicrosoftGraphClientWithCredential(oboCredential, [".default"]);
      
      const profile: any = await graphClient.api("/me").get();