为 Fabric 应用配置 Fabric SSO 身份验证

通过Fabric门户、直接委派令牌交换或可信的外部父门户,为Fabric应用设置Microsoft Entra登录。 这些认证路径使用Microsoft Entra,且不支持任意的身份提供者。

先决条件

Fabric SSO 的工作原理

Fabric 单点登录 (SSO) 使用应用程序与 Fabric 门户之间基于 postMessage 的安全交接机制。 没有重定向或回调页面:

  1. 您的应用会在弹出窗口中打开 Fabric 门户,并注册一个 postMessage 监听器。
  2. 用户在Fabric门户中通过Microsoft Entra ID进行身份验证。
  3. Fabric扩展通过 window.opener.postMessage() 将移交代码发送回应用。
  4. SDK 交换 Rayfin 会话令牌的交接代码并创建会话。
  5. Fabric弹出窗口会自动关闭。

该流程通过 PKCE(代码交换证明密钥)、state 随机数和 postMessage 来源验证来保护,以防止授权码拦截和跨站点请求伪造。

启用Fabric身份验证

将Fabric身份验证配置添加到 rayfin/rayfin.yml 文件:

services:
  auth:
    enabled: true
    allowedRedirectUris:
      - http://localhost:5173
    fabric:
      enabled: true

对于已部署的应用程序,请重新部署以推送更新的设置:

npx rayfin up

对于已部署的应用,npx rayfin up会将已部署应用的源添加到allowedRedirectUris。 关于配置和安全指导,请参见配置认证重定向URI。

安装Fabric身份验证提供程序(可选)

使用 npm create @microsoft/rayfin@latest 创建的项目已包含 @microsoft/rayfin-auth-provider-fabric。 仅当你要为尚未包含该软件包的项目添加 Fabric 身份验证时,才需要手动安装该软件包:

npm install @microsoft/rayfin-auth-provider-fabric

将登录和注册添加到应用

Fabric SSO 对登录和注册使用单个 API:ensureSignedInWithFabric()。 当用户首次登录时,Fabric会根据用户的Microsoft Entra ID标识自动为其预配 Rayfin 会话-没有单独的注册呼叫。 同一代码路径也适用于回访用户。

可以使用 VS Code 中的GitHub Copilot手动添加此代码或生成此代码。

手动添加登录

在用户手势处理程序中调用 ensureSignedInWithFabric()(例如,在按钮选择事件中):

import { RayfinClient } from '@microsoft/rayfin-client';
import { ensureSignedInWithFabric } from '@microsoft/rayfin-auth-provider-fabric';

const client = new RayfinClient({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
});

const fabricOptions = {
  workspaceId: import.meta.env.VITE_FABRIC_WORKSPACE_ID,
  projectId: import.meta.env.VITE_FABRIC_ITEM_ID,
  fabricPortalUrl: import.meta.env.VITE_FABRIC_PORTAL_URL,
  returnOrigin: window.location.origin,
};

async function handleSignIn() {
  // Signs in existing users and provisions new users on first sign-in.
  const session = await ensureSignedInWithFabric(client.auth, fabricOptions);
  if (session.isAuthenticated && session.user) {
    console.log('Signed in as:', session.user.email);
  }
}

必须从同步用户手势处理程序调用该函数,以避免弹出阻止程序。 在页面加载时调用它,或者在用户交互之前的异步调用链中调用它,都会触发浏览器的弹窗保护机制。

returnOrigin 必须是裸源(方案和主机,无路径),例如 https://app.contoso.com。 SDK 使用它来验证传入 postMessage 事件。

手动添加注销

调用 client.auth.signOut() 以结束会话并清除缓存的令牌:

async function handleSignOut() {
  await client.auth.signOut();
  console.log('Signed out');
}

订阅会话变更,以便在登录或注销完成时更新用户界面:

client.auth.onSessionChange((session) => {
  console.log('Session changed:', session?.isAuthenticated ? 'signed in' : 'signed out');
});

使用 GitHub Copilot 生成登录和注册

如果在 VS Code 中使用 GitHub Copilot,请在 Fabric Apps 项目中打开Copilot 对话助手,并使用此类提示来搭建身份验证代码的基架。 Copilot 遵循 Fabric VS Code 扩展中附带的 Rayfin 技能里的模式。

目标 示例 Copilot 提示词
添加登录按钮 Add a Sign in with Fabric button to my React app using ensureSignedInWithFabric from @microsoft/rayfin-auth-provider-fabric. Read workspaceId, projectId, and fabricPortalUrl from VITE_* env vars and set returnOrigin to window.location.origin.
添加注销按钮 Add a Sign out button that calls client.auth.signOut() and updates the UI when the session ends.
添加一个支持身份验证的 React Hook Create a useFabricAuth React hook that exposes session, signIn, signOut, and isAuthenticated, using ensureSignedInWithFabric and client.auth.onSessionChange.
支持嵌入式模式 Update my app's entry point to call initEmbeddedAuth on page load so users signed in through the Fabric portal don't have to click Sign in again.
限制路由 Wrap the /dashboard route so it calls ensureSignedInWithFabric before rendering and redirects unauthenticated users to a sign-in page.

Copilot生成代码后,请查看编辑并确保:

  • 调用 ensureSignedInWithFabric() 在用户手势处理程序(例如 onClick)内运行,而不是在页面加载时运行。
  • returnOrigin是一个裸源,并且与allowedRedirectUris中的rayfin/rayfin.yml条目之一匹配。
  • 从 @microsoft/rayfin-auth-provider-fabric 导入(而不是从已弃用的回调辅助函数导入)。

在 Fabric iframe 中使用嵌入式模式

当应用在 Fabric iframe 内加载(例如,当用户从 Fabric 门户打开应用时),请使用嵌入模式而不是弹出窗口流:

  • 嵌入模式通过 postMessage 从父框架获取会话。
  • 它不会打开弹出窗口,不需要用户手势,因此可以安全地调用页面加载。
  • SDK 从 ?fabricEmbedded=true URL 中自动检测嵌入模式。 还可以通过在选项中设置 fabricEmbedded: true 来强制它。

在应用启动中提前调用 initEmbeddedAuth() :

import { initEmbeddedAuth } from '@microsoft/rayfin-auth-provider-fabric';
import { client } from './lib/rayfin';

const session = await initEmbeddedAuth(client.auth, {
  workspaceId: import.meta.env.VITE_FABRIC_WORKSPACE_ID,
  projectId: import.meta.env.VITE_FABRIC_ITEM_ID,
  fabricPortalUrl: import.meta.env.VITE_FABRIC_PORTAL_URL,
  returnOrigin: window.location.origin,
});

if (session) {
  console.log('Signed in via embedded mode:', session.user?.email);
}

initEmbeddedAuth() 会在应用未以嵌入模式运行时返回 null,因此可以安全地无条件调用。 ensureSignedInWithFabric() 还会在回退到弹出窗口流之前自动尝试嵌入模式。

在 React 中使用Fabric身份验证

创建集成登录、注册和注销的自定义挂钩:

import { useState, useEffect, useCallback } from 'react';
import { ensureSignedInWithFabric } from '@microsoft/rayfin-auth-provider-fabric';
import { client } from './lib/rayfin';

const fabricOptions = {
  workspaceId: import.meta.env.VITE_FABRIC_WORKSPACE_ID,
  projectId: import.meta.env.VITE_FABRIC_ITEM_ID,
  fabricPortalUrl: import.meta.env.VITE_FABRIC_PORTAL_URL,
  returnOrigin: window.location.origin,
};

export function useFabricAuth() {
  const [session, setSession] = useState(client.auth.getSession());

  useEffect(() => client.auth.onSessionChange(setSession), []);

  // Signs in existing users and provisions new users on first sign-in.
  const signIn = useCallback(async () => {
    const result = await ensureSignedInWithFabric(client.auth, fabricOptions);
    setSession(result);
    return result;
  }, []);

  const signOut = useCallback(async () => {
    await client.auth.signOut();
  }, []);

  return {
    session,
    signIn,
    signOut,
    isAuthenticated: session?.isAuthenticated ?? false,
  };
}

在组件中使用挂钩:

function App() {
  const { isAuthenticated, signIn, signOut } = useFabricAuth();

  if (!isAuthenticated) {
    return <button onClick={signIn}>Sign in with Fabric</button>;
  }

  return (
    <>
      <Dashboard />
      <button onClick={signOut}>Sign out</button>
    </>
  );
}

使用现有的 Microsoft Entra 令牌登录

当你的浏览器或 Node.js 应用已经获得委托的 Microsoft Entra 访问令牌时,请使用 signInWithEntraToken()。 它会在你现有的 client.auth 上建立一个 Rayfin 会话,没有弹窗、iframe、重定向或移交代码。

启用外部 Entra Exchange

在目标应用的rayfin/rayfin.yml文件中设置以下选项,然后使用npx rayfin up重新部署:

services:
  auth:
    enabled: true
    fabric:
      enabled: true
      externalEntraExchange: true

目标Fabric环境必须支持外部交换。 所提供的令牌必须:

  • 应为委派的用户访问令牌,而不是仅应用的服务主体令牌。
  • 针对部署所接受的 Fabric 或 Power BI 资源。
  • 包含委托 Item.Execute.All 作用域。
  • 应在目标项的所属租户中签发。

用户还必须对应用项目拥有 执行 权限。 对于生产环境的 Power BI,请通过你的身份库提出https://analysis.windows.net/powerbi/api/Item.Execute.All请求。 SDK不获取Entra令牌,也不处理同意。

浏览器使用

使用与数据客户端相同的可信HTTPS后端URL和可发布密钥:

import { signInWithEntraToken } from '@microsoft/rayfin-auth-provider-fabric';
import { client } from './lib/rayfin';

async function signInWithDelegatedToken(entraToken: string) {
  const session = await signInWithEntraToken(client.auth, { entraToken });
  return session;
}

传递原始访问令牌,不加 Bearer 前缀。 辅助工具使用客户端的后端基础URL,保留其部署路径,并附加 /api/auth/v1/brokered/token。 基础 URL 必须是绝对 HTTPS URL,且不包含凭据、查询或片段。 不要使用静态托管URL、相对代理URL或不受信任调用者提供的端点。

同一客户端的数据和函数调用会自动使用已交换的 Rayfin 会话。 浏览器交换还要求服务的CORS策略允许你的来源地址和授权头。

在用户界面中处理被拒绝的登录,并在允许请求账户操作前显示错误信息。 失败的交换可能会在内存中留下一个较早的未过期会话;不要将其视为新选用户的成功认证。

Node.js 使用与会话隔离

你可以在不使用 window、document或 localStorage的情况下导入并使用该辅助工具。 对于独立的SDK集成,创建 Auth 并将其附加到API客户端:

import { Auth } from '@microsoft/rayfin-auth';
import { ApiClient } from '@microsoft/rayfin-lib';
import { signInWithEntraToken } from '@microsoft/rayfin-auth-provider-fabric';

async function authenticateUser(
  rayfinEndpoint: string,
  publishableKey: string,
  entraToken: string,
) {
  const apiClient = new ApiClient({ baseUrl: rayfinEndpoint, publishableKey });
  const auth = new Auth(apiClient, { storage: false });
  auth.attachToClient(apiClient);

  try {
    const session = await signInWithEntraToken(auth, { entraToken });
    // Perform this user's SDK operations with apiClient inside this scope.
    return session.isAuthenticated;
  } finally {
    auth.destroy();
  }
}

使用受信任且已配置的rayfinEndpoint,而不是调用方控制的 URL。 为每个用户或请求创建独立实例,将会话保存在内存中,不再需要时销毁它们。 切勿在用户之间共享可变的已登录客户端。 对于 RayfinClient,请使用 authStorage: false 以实现相同的仅内存行为。 RayfinServerClient 不会暴露 auth,也不能直接传给这个辅助函数。

SDK 不会持久化提供的 Entra 令牌。 正常会话刷新使用Rayfin刷新令牌;如果无法再刷新,则获取新的Entra令牌并显式交换。

嵌入外部父级门户

当 Fabric 外部的门户嵌入你的应用并且已具有委托的 Entra 身份时,使用 @microsoft/rayfin-embed-host。 父级中介认证;iframe只接收一次性交接代码,而非父级的 Entra 令牌。

启用 externalEntraExchange 并满足前文所述的委托令牌、租户、范围和项 执行 的前提条件。 授予访问父页面并不授予对 Fabric 应用的访问权限。

在父级门户中安装宿主包:

npm install @microsoft/rayfin-embed-host

在挂载iframe 前 注册主机,因为iframe只发送一次准备信号:

import { createEmbedHost } from '@microsoft/rayfin-embed-host';

function mountFabricApp(getAccessToken: () => Promise<string>) {
  const appUrl = 'https://my-fabric-app.example.com';
  const host = createEmbedHost({
    allowedOrigins: [new URL(appUrl).origin],
    getAccessToken,
  });

  const iframe = document.createElement('iframe');
  iframe.src = appUrl;
  document.body.append(iframe);

  return () => {
    iframe.remove();
    host.dispose();
  };
}

为当前父用户提供令牌获取功能。 在嵌入式应用中,即使 initEmbeddedAuth() 已经显示已有用户,也要先调用并等待 getSession(),再恢复存储的会话或渲染认证内容。 存储的用户可能与父级的当前用户不同。 主机确认检测外部嵌入;该路径无需 fabricEmbedded 查询标志。

使用精确的可信来源,包括 scheme、host 和 port,在 allowedOrigins。 主机在发起授权调用前,会同时验证浏览器认证的iframe消息起源和请求的返回来源。 不要接受任意由来电者提供的允许列表。 将 Entra 令牌保留在父级授权路径中,绝不要通过 postMessage 发送它,并在移除嵌入时调用 host.dispose()。

API 参考

ensureSignedInWithFabric

function ensureSignedInWithFabric(
  auth: Auth,
  options: FabricAuthOptions
): Promise<OpaqueSession>;

实现四步身份验证瀑布:

  1. 如果已通过身份验证,则返回现有会话。
  2. 尝试通过刷新令牌进行静默刷新。
  3. 嵌入模式 - 如果在 Fabric iframe 中运行,则通过 postMessage 获取会话到父帧。
  4. 在弹出窗口中打开 Fabric 门户(弹出流程),并等待 postMessage 切换完成。

步骤 1 到 3 可以在页面加载时安全地调用。 步骤 4 将打开弹出窗口,必须在用户手势处理程序中运行。

FabricAuthOptions

财产 类型 Description
workspaceId string Fabric工作区 ID。
projectId string Fabric应用项 ID。
fabricPortalUrl string Fabric 门户基本 URL(例如,https://app.fabric.microsoft.com)。
returnOrigin string 应用的交付来源 postMessage (例如, window.location.origin)。 必须是裸源(方案和主机,无路径)。
fabricEmbedded boolean(可选) 强制嵌入模式。 从 ?fabricEmbedded=true URL 中自动检测到。

帮助函数

Function Description
initEmbeddedAuth(auth, options) Fabric 或已确认的外部父主机的页面加载安全身份验证。 成功时返回会话,或者 null 当嵌入认证不可用时。
initiateFabricLogin(auth, options) 低级别弹出窗口流。 在弹出窗口中使用 PKCE 参数打开 Fabric 门户,并监听 postMessage 交接。
isEmbeddedMode(options) 如果应用在嵌入式模式下运行(Fabric iframe),则返回 true。
signInWithEntraToken(auth, { entraToken }) 交换委托的Entra令牌,并在浏览器或 Node.js中建立会话。 不需要 FabricAuthOptions。

安全功能

  • PKCE S256 ——交接流程生成加密代码验证器和质询,以防止授权码被截获。 直接 Entra 令牌交换不使用 PKCE。
  • State 随机数 – 随机生成的随机数会将交接响应与发起该请求的选项卡关联起来,从而防止跨站点请求伪造。
  • postMessage 源验证 – SDK 对 event.origin 传入消息进行验证,并拒绝来自意外源的消息。
  • 自动清理 – PKCE 状态会在 5 分钟后过期,并在下一次流程执行时由垃圾回收机制清理。
  • 流程超时 – 如果在 5 分钟内未收到交接消息,弹出窗口流程将超时。

排查身份验证问题

浏览器阻止了Fabric门户窗口。 确保 ensureSignedInWithFabric() 从同步用户手势处理程序(例如按钮 onClick)调用。 在用户交互之前,请勿在页面加载或异步链中调用它。

会话未持久化

确认 RayfinClient 已配置正确的 baseUrl 和 publishableKey。 回调选项卡和原始选项卡必须共享相同的源,才能BroadcastChannellocalStorage正常工作。

身份验证在长时间延迟后失败

登录流将在 5 分钟后过期。 如果你开始登录流程,但未在该时限内完成,整个流程将失败。 关闭弹出窗口,再次选择登录按钮以启动新流。