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

在Microsoft Teams标签页应用的iframe中传递SSO令牌实现认证

在Microsoft Teams标签页应用中向iframe传递SSO令牌实现认证的方案

完全可行,以下是几种具体实现方案,可根据你的场景选择:

方法1:通过URL参数传递令牌(简单直接)

这是最易实现的方式,适合同源或低敏感场景,但需注意URL参数可能被日志记录,需评估安全风险。

修改你的代码,确保令牌获取完成后再渲染iframe,并将令牌拼接进iframe的地址:

useEffect(() => {
  microsoftTeams.initialize();
  microsoftTeams.authentication.getAuthToken({
    successCallback: (result) => {
      console.log("result", result);
      setToken(result);
    },
    failureCallback: (reason) => {
      console.log("reason", reason);
    },
  });
}, []);

return (
  <div>
    <h1 className="mainTitle">{token}</h1>
    {/* 仅当token存在时渲染iframe,避免加载时令牌未就绪 */}
    {token && (
      <iframe
        src={`mysiteurl?token=${encodeURIComponent(token)}`}
        title="XYZ out page"
        allowFullScreen
        className="iframe"
      ></iframe>
    )}
  </div>
);

内嵌网站只需从URL参数中提取token,即可用该令牌完成Microsoft SSO认证流程。

方法2:通过postMessage跨域传递令牌(更安全)

如果Teams标签页和内嵌网站不同源,postMessage是更安全的方案,不会将令牌暴露在URL中。

Teams标签页应用端修改:

添加iframe加载完成事件,发送令牌到内嵌网站:

useEffect(() => {
  microsoftTeams.initialize();
  microsoftTeams.authentication.getAuthToken({
    successCallback: (result) => {
      console.log("result", result);
      setToken(result);
    },
    failureCallback: (reason) => {
      console.log("reason", reason);
    },
  });
}, []);

const handleIframeLoad = (e) => {
  // 仅向指定域名发送消息,避免安全风险
  e.target.contentWindow.postMessage(
    { type: 'MS_SSO_TOKEN', token: token },
    'https://your-embedded-site-domain.com' // 替换为内嵌网站的实际域名
  );
};

return (
  <div>
    <h1 className="mainTitle">{token}</h1>
    {token && (
      <iframe
        src="mysiteurl"
        title="XYZ out page"
        allowFullScreen
        className="iframe"
        onLoad={handleIframeLoad}
      ></iframe>
    )}
  </div>
);

内嵌网站端代码:

添加message事件监听,接收令牌并处理认证:

window.addEventListener('message', (event) => {
  // 验证消息来源,确保是可信的Teams标签页域名
  if (event.origin !== 'https://your-teams-tab-domain.com') return;
  
  if (event.data.type === 'MS_SSO_TOKEN' && event.data.token) {
    // 使用接收到的令牌完成认证逻辑
    console.log('Received SSO token:', event.data.token);
    // 例如:调用认证接口,或存入localStorage供后续使用
    localStorage.setItem('ms-sso-token', event.data.token);
    yourAuthFunction(event.data.token);
  }
});

方法3:同源下直接操作iframe内容(仅限同源场景)

如果Teams标签页和内嵌网站同源,可直接访问iframe的contentWindow,将令牌注入到内嵌网站的上下文:

const handleIframeLoad = (e) => {
  // 同源下可直接操作iframe的window对象
  e.target.contentWindow.localStorage.setItem('ms-sso-token', token);
  // 或直接调用内嵌网站的认证方法
  e.target.contentWindow.initSSOAuth(token);
};

安全注意事项

  • 始终使用HTTPS传输令牌,避免明文泄露
  • 限制令牌的有效期,遵循最小权限原则
  • postMessage时指定精确的targetOrigin,接收时验证event.origin,防止恶意网站窃取令牌
  • 高敏感场景优先使用postMessage,避免URL参数传递令牌

内容的提问来源于stack exchange,提问作者Matteo Robert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:45:37