You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular17集成MSAL+mgt-teamsfx-provider在Teams内令牌获取失败

Angular 17 + MGT TeamsFx Provider 在Teams内部认证失败求助

项目依赖版本

{
  "@angular/animations": "^17.3.3",
  "@angular/common": "^17.3.3",
  "@angular/compiler": "^17.3.3",
  "@angular/core": "^17.3.3",
  "@angular/forms": "^17.3.3",
  "@angular/platform-browser": "^17.3.3",
  "@angular/platform-browser-dynamic": "^17.3.3",
  "@angular/router": "^17.3.3",
  "@angular/service-worker": "^17.3.3",
  "@azure/msal-angular": "^3.0.15",
  "@azure/msal-browser": "^3.11.1",
  "@microsoft/mgt": "^4.2.1",
  "@microsoft/mgt-element": "^4.2.1",
  "@microsoft/mgt-teamsfx-provider": "^4.2.1",
  "@microsoft/teams-js": "^2.21.0",
  "@microsoft/teamsfx": "^2.3.1",
  "bootstrap": "^5.3.3",
  "bootstrap-icons": "^1.11.3",
  "moment": "^2.30.1",
  "ngx-device-detector": "^7.0.0",
  "primeflex": "^3.3.1",
  "primeicons": "^7.0.0",
  "primeng": "^17.12.0",
  "quill": "^1.3.7",
  "rxjs": "~7.8.1",
  "tslib": "^2.6.2",
  "zone.js": "~0.14.4"
}

问题现象

  • @microsoft/mgt-teamsfx-provider官方示例代码无法正常运行
  • Angular 17应用在Teams外部运行时,MGT组件加载正常;但在Teams内部运行时,MGT组件完全无法工作,报错如下:

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.

Auth-Start.html 代码

<!--This file is used during the Teams authentication flow to assist with retrieval of the access token.-->
<!--If you're not familiar with this, do not alter or remove this file from your project.-->

<html>

<head>
  <title>Login Start Page</title>
  <meta charset="utf-8" />
</head>

<body>

  <script src="https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js"
    crossorigin="anonymous">
    </script>

  <script type="text/javascript"
    src="https://cdn.jsdelivr.net/npm/@azure/msal-browser@3.11.1/lib/msal-browser.min.js"
    crossorigin="anonymous">
    </script>

  <script type="text/javascript">
    microsoftTeams.app.initialize().then(() => {
      console.log("auth-start.html, microsoftTeams.app.initialize()");
      microsoftTeams.app.getContext().then(async (context) => {
        console.log("auth-start.html, microsoftTeams.app.getContext()");
        // Generate random state string and store it, so we can verify it in the callback
        var currentURL = new URL(window.location);
        console.log("auth-start.html, currentURL %s", currentURL);

        var clientId = currentURL.searchParams.get("clientId");
        console.log("auth-start.html, clientId %s", clientId);

        var scope = currentURL.searchParams.get("scope");
        console.log("auth-start.html, scope %s", scope);

        var loginHint = currentURL.searchParams.get("loginHint");
        console.log("auth-start.html, loginHint %s", loginHint);

        const msalConfig = {
          auth: {
            clientId: clientId,
            authority: `https://login.microsoftonline.com/${context.user.tenant.id}`,
            navigateToLoginRequestUrl: false
          },
          cache: {
            cacheLocation: "sessionStorage",
          }
        }

        const msalInstance = new msal.PublicClientApplication(msalConfig);
        await msalInstance.initialize(); // new with 3.X
        console.log("auth-start.html, msalInstance initialized %O", msalInstance);

        //const msalInstance = await msal.PublicClientApplication.createPublicClientApplication(msalConfig);

        const scopesArray = scope.split(" ");
        const scopesRequest = {
          scopes: scopesArray,
          redirectUri: window.location.origin + `/auth-end.html?clientId=${clientId}`,
          loginHint: loginHint
        };
        console.log("auth-start.html, scopesRequest %O", scopesRequest);
        await msalInstance.loginRedirect(scopesRequest);
      });
    });
  </script>
</body>

</html>

Auth-End.html 代码

<!--This file is used during the Teams authentication flow to assist with retrieval of the access token.-->
<!--If you're not familiar with this, do not alter or remove this file from your project.-->
<html>

<head>
  <title>Login End Page</title>
  <meta charset="utf-8" />
</head>

<body>

  <script src="https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js"
    crossorigin="anonymous">
    </script>

  <script type="text/javascript"
    src="https://cdn.jsdelivr.net/npm/@azure/msal-browser@3.11.1/lib/msal-browser.min.js"
    crossorigin="anonymous">
    </script>

  <script type="text/javascript">
    var currentURL = new URL(window.location);
    console.log("auth-end.html, currentURL %s", currentURL);

    var clientId = currentURL.searchParams.get("clientId");
    console.log("auth-end.html, clientId %s", clientId);

    microsoftTeams.app.initialize().then(() => {
      console.log("auth-end.html, microsoftTeams.app.initialize()");
      microsoftTeams.app.getContext().then(async (context) => {
        console.log("auth-end.html, microsoftTeams.app.getContext()");
        const msalConfig = {
          auth: {
            clientId: clientId,
            authority: `https://login.microsoftonline.com/${context.tid}`,
            navigateToLoginRequestUrl: false
          },
          cache: {
            cacheLocation: "sessionStorage",
          }
        }

        //https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/acquire-token.md
        //https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/v2-migration.md
        //https://github.com/OfficeDev/TeamsFx/wiki/

        //const msalInstance = new window.msal.PublicClientApplication(msalConfig);

        const msalInstance = new msal.PublicClientApplication(msalConfig);
        await msalInstance.initialize(); // new with 3.X
        console.log("auth-end.html, msalInstance initialized %O", msalInstance);
        
        msalInstance.handleRedirectPromise().then((tokenResponse) => {
          if (tokenResponse !== null) {
            console.log("auth-end.html, tokenResponse %O", tokenResponse);
            //alert(tokenResponse.accessToken);
            microsoftTeams.authentication.notifySuccess(JSON.stringify({
              sessionStorage: sessionStorage
            }));
            //microsoftTeams.authentication.notifySuccess();
            //sessionStorage.setItem(StorageKeys.accessToken, tokenResponse.accessToken);
          } else {
            microsoftTeams.authentication.notifyFailure("Get empty response.");
          }
        }).catch((error) => {
          microsoftTeams.authentication.notifyFailure(JSON.stringify(error));
        });
      });
    });
  </script>
</body>

</html>

已尝试操作

已查阅MSAL Browser、MGT TeamsFx Provider、MGT及MGT Element的最新文档,但未找到有效解决方案,恳请提供技术帮助。


内容的提问来源于stack exchange,提问作者Tolga Köseoğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:45:56