Rayfin

@microsoft/rayfin-auth-provider-fabric

Fabric auth provider reference for Fabric SSO, direct Entra token exchange, embedded handoff, external embed support, and sign-in error codes.

@microsoft/rayfin-auth-provider-fabric signs Rayfin users in with Microsoft Entra ID. Browser helpers broker through Fabric SSO. signInWithEntraToken() exchanges an existing delegated Entra token directly in browsers or Node.js. New in 1.36

The package operates on an Auth instance from @microsoft/rayfin-auth — usually client.auth from a RayfinClient created with browserSession().

Note

This package's catalog listing can mention MSAL, but the installed implementation does not depend on MSAL.js. Browser broker flows implement PKCE S256 and postMessage against Fabric. Direct token sign-in expects your code to obtain the delegated Entra token.

Installation

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

The package declares an exports map; import from the package root only. Changed in 2.0

Where each flow works

FlowRuntimeUse when
ensureSignedInWithFabric popup flowBrowserThe app needs Fabric to perform interactive sign-in from a standalone origin such as http://localhost:5173 or the deployed site.
initEmbeddedAuth Fabric iframe flowBrowser iframeThe app is loaded inside the Fabric portal and should sign in without a popup.
initEmbeddedAuth external embed flowBrowser iframeA third-party parent page acknowledges the external-embed handshake and brokers auth for the iframe. New in 1.36
signInWithEntraTokenBrowser or Node.jsYour code already has a delegated Entra token and wants to exchange it for a Rayfin session. New in 1.36
signInWithBrokeredTokenBrowser or Node.jsA trusted caller already obtained a Rayfin token response from the brokered exchange endpoint. New in 1.36

Popup and embedded Fabric SSO require a Rayfin backend deployed to Fabric. The popup flow works from any origin listed in allowedRedirectUris. The embedded Fabric flow requires the app to be loaded inside a Fabric iframe.

Exports

export type { FabricAuthOptions };
export type { EntraTokenSignInOptions };
export type { PostMessageHandoffResult };
export { bridgeFabricCallback };
export { embeddedFabricLogin };
export { ensureSignedInWithFabric };
export { initEmbeddedAuth };
export { initiateFabricLogin };
export { requestHandoff };
export { signInWithBrokeredToken, signInWithEntraToken };

The public root can be imported in Node.js. Browser broker helpers still require browser APIs such as window.open(), postMessage, BroadcastChannel, and window.location.

FabricAuthOptions

interface FabricAuthOptions {
  workspaceId: string;
  projectId: string;
  fabricPortalUrl: string;
  tenantId?: string;
  returnOrigin: string;
  callbackUrl?: string;
  fabricEmbedded?: boolean;
}
OptionTypeDescription
workspaceIdstringFabric workspace ID.
projectIdstringFabric project or AppBackend artifact ID.
fabricPortalUrlstringFabric portal URL. Existing path and query parameters are preserved when the broker URL is built.
tenantIdstringMicrosoft Entra tenant that owns the Fabric item. Added to the broker URL as ctid, so sign-in opens in that tenant instead of first discovering the user's home tenant. Omit it when the tenant is unknown. New in 2.0
returnOriginstringBare origin of the app that initiated auth, such as window.location.origin.
callbackUrlstringLegacy redirect callback URL. Defaults to ${returnOrigin}/auth/callback. Deprecated for postMessage-capable portals.
fabricEmbeddedbooleanForces the Fabric embedded flow. The SDK also detects ?fabricEmbedded=true and a flag it remembers in sessionStorage; false does not turn that detection off. These Fabric hints take precedence over external-host discovery. Changed in 2.0

Pass tenantId from VITE_FABRIC_TENANT_ID, or from client.runtimeConfig?.tenantId when you resolve deployment values with resolveRayfinConfig().

ensureSignedInWithFabric

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

Browser-only primary entry point for Fabric SSO. It first detects the host: Fabric embedding from the Fabric hints, or — only when there are none — an external embed host that acknowledges a readiness message within 300 ms. Changed in 2.0 It then runs a waterfall where the first successful step short-circuits the rest:

  1. Return a safe existing session.
  2. Try auth.refreshSession() if a refresh token exists.
  3. Use embedded postMessage handoff if Fabric embedded mode or external-embed classification applies. Changed in 1.36
  4. Open the Fabric broker popup.

Steps 1 and 2 are skipped for an external embed host, and for Fabric embedding without a viewer hint from the host until a handoff completes in the current page load. Step 4 calls window.open(), so call this function directly from a user gesture. It rejects with an AuthError; show error.message to the user.

src/auth/signInButton.ts
import { browserSession } from '@microsoft/rayfin-auth';
import { ensureSignedInWithFabric } from '@microsoft/rayfin-auth-provider-fabric';
import { RayfinClient } from '@microsoft/rayfin-client';

const client = RayfinClient.create({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
  auth: browserSession({ storage: true }),
});

const signInError = document.querySelector<HTMLElement>('#sign-in-error');

document.querySelector('#sign-in')?.addEventListener('click', async () => {
  if (signInError) signInError.textContent = '';
  try {
    const session = await ensureSignedInWithFabric(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,
      tenantId: import.meta.env.VITE_FABRIC_TENANT_ID,
      returnOrigin: window.location.origin,
    });
    console.log('Signed in:', session.user?.email);
  } catch (error) {
    // Show the user-safe message; never swallow a sign-in error.
    if (signInError) {
      signInError.textContent = error instanceof Error ? error.message : 'Sign-in failed.';
    }
  }
});

The client is created with RayfinClient.create() and browserSession(). Changed in 2.0

initEmbeddedAuth

function initEmbeddedAuth(
  auth: Auth,
  options: FabricAuthOptions
): Promise<OpaqueSession | null>;

Browser-only startup helper. It never opens a popup and never rejects. It checks the Fabric hints first; only when there are none does it run the one-shot external-embed handshake. Changed in 2.0

It returns null when no embedded scenario applies, and also when embedded sign-in fails — after logging a console warning. Await it before trusting a stored session in iframe scenarios, and show a sign-in button when it returns null so the click reports the error.

src/auth/bootstrap.ts
import { initEmbeddedAuth } from '@microsoft/rayfin-auth-provider-fabric';
import { client } from '../services/rayfinClient';
import { fabricOptions } from './fabricOptions';

const session = await initEmbeddedAuth(client.auth, fabricOptions);
if (session) {
  console.log('Embedded session established:', session.user?.email);
}

Warning

Import @microsoft/rayfin-auth-provider-fabric with a static import, not only a dynamic import(). The package captures the ?fabricEmbedded=true URL flag into sessionStorage during module load.

initiateFabricLogin

function initiateFabricLogin(auth: Auth, options: FabricAuthOptions): Promise<void>;

Low-level popup helper used by ensureSignedInWithFabric(). It opens the broker, sends the PKCE challenge after brokeredAuth.ready, receives brokeredAuth.handoff, exchanges the handoff code, and installs the session. It rejects with TAB_BLOCKED when the popup cannot open, FABRIC_AUTH_POPUP_CLOSED about one second after the user closes the sign-in window, FABRIC_AUTH_TIMEOUT after five minutes, or the code the broker reports. Changed in 2.0 Most apps should use ensureSignedInWithFabric() instead.

signInWithEntraToken

interface EntraTokenSignInOptions {
  entraToken: string;
}

function signInWithEntraToken(
  auth: Auth,
  options: EntraTokenSignInOptions
): Promise<OpaqueSession>;

Exchanges an existing delegated Entra token for a Rayfin session. It works in browsers and Node.js and does not require FabricAuthOptions, a popup, or an iframe. New in 1.36

Pass client.auth from a client created with browserSession(), or a standalone Auth. A client created with suppliedToken() has no client.auth. Changed in 2.0

The Auth instance's ApiClient must point at an absolute HTTPS AppBackend workload API base URL. The helper resolves /api/auth/v1/brokered/token against that base and rejects URLs with credentials, query strings, fragments, whitespace, backslashes, or non-HTTPS protocols.

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

const apiClient = new ApiClient({
  baseUrl: process.env.RAYFIN_API_URL!,
  publishableKey: process.env.RAYFIN_PUBLISHABLE_KEY!,
});

const auth = new Auth(apiClient, { storage: false });
auth.attachToClient(apiClient);

try {
  const session = await signInWithEntraToken(auth, {
    entraToken: process.env.ENTRA_ACCESS_TOKEN!,
  });
  console.log('Authenticated:', session.isAuthenticated);
} finally {
  auth.destroy();
}

See Sign in with an Entra token for a RayfinClient version that queries data as the user.

signInWithBrokeredToken

function signInWithBrokeredToken(
  auth: Auth,
  tokenResponse: TokenResponse
): Promise<OpaqueSession>;

Installs a token response that was already obtained from POST /api/auth/v1/brokered/token by a trusted caller. It performs no network request. Prefer signInWithEntraToken() when the caller has the raw Entra token and an HTTPS-reachable backend. New in 1.36

The local development adapter uses this helper to install a token response obtained through the developer's rayfin login session.

Embedded transport helpers

function embeddedFabricLogin(auth: Auth, options: FabricAuthOptions): Promise<void>;

function requestHandoff(params: {
  callbackUrl: string;
  codeChallenge: string;
  codeChallengeMethod: string;
  state: string;
  timeoutMs?: number;
  brokeredAuthorizeUrl?: string;
  artifactId?: string;
  targetOrigin?: string;
}): Promise<{ handoffCode: string; state: string }>;

These are low-level browser helpers. In external embed mode, embeddedFabricLogin() adds brokeredAuthorizeUrl, artifactId, and a pinned targetOrigin to the handoff request. Normal Fabric embedded payloads remain unchanged. Changed in 1.36 When a Fabric hint is present, embeddedFabricLogin() uses the Fabric payload even if an external host acknowledged earlier. Changed in 2.0

Most applications should call initEmbeddedAuth() rather than these helpers directly.

bridgeFabricCallback

function bridgeFabricCallback(): boolean;

Legacy callback bridge for Fabric portals that redirect the popup to an app callback page. It forwards any Fabric handoff parameters found in the URL back to the opener window and closes the popup. Modern Fabric broker handoff uses postMessage.

Environment variables

rayfin dev and rayfin up write the Fabric coordinates needed for FabricAuthOptions. For Vite apps, framework environment generation maps them to these names:

Source variable (rayfin/.env)Vite variable (.env.local)Maps to
RAYFIN_PUBLIC_ITEM_IDVITE_FABRIC_ITEM_IDprojectId
RAYFIN_PUBLIC_WORKSPACE_IDVITE_FABRIC_WORKSPACE_IDworkspaceId
RAYFIN_PUBLIC_PORTAL_URLVITE_FABRIC_PORTAL_URLfabricPortalUrl
RAYFIN_PUBLIC_TENANT_IDVITE_FABRIC_TENANT_IDtenantId New in 2.0

See Fabric SSO and rayfin.yml auth configuration.

Error handling

Sign-in functions reject with AuthError from @microsoft/rayfin-lib, which @microsoft/rayfin-client re-exports. error.message is a user-safe description intended for display: catch every sign-in call that can reject and show it in the sign-in UI. Use error.code only for branching logic or telemetry. initEmbeddedAuth() resolves to null instead of rejecting.

Browser broker errors

CodeMeaning
ACCESS_DENIEDThe signed-in user does not have access to this app.
TOKEN_ACQUISITION_FAILEDThe broker could not acquire a Fabric token for the user.
AUTHORIZE_FAILEDThe broker's authorize step failed with a server, network, or unexpected error.
AUTH_FAILEDAuthentication failed in the broker.
INVALID_CALLBACK_URLThe app's return origin or callback URL is not allowed.
RATE_LIMITEDToo many sign-in requests from the embedded app. Wait and retry.
OWNER_LOGIN_REQUIREDOnly the app owner can sign in while the app's Functions use delegated authentication.
APP_DEPLOYMENT_REQUIREDThe app's Functions must be deployed or redeployed before users can sign in.
APP_ADMIN_BLOCKEDA tenant or capacity admin has blocked the app.
FABRIC_AUTH_FAILEDThe broker reported a failure without a specific code.
FABRIC_AUTH_POPUP_CLOSEDThe user closed the sign-in window before sign-in completed. New in 2.0
FABRIC_AUTH_TIMEOUTThe popup handoff timed out after five minutes.
TAB_BLOCKEDThe broker popup could not open.
PKCE_CHALLENGE_FAILEDPKCE challenge generation failed.
CHALLENGE_DELIVERY_FAILEDThe SDK could not post the PKCE challenge to the broker frame.
MISSING_WORKSPACE_ID, MISSING_PROJECT_ID, MISSING_RETURN_ORIGIN, MISSING_FABRIC_PORTAL_URLA required FabricAuthOptions value is missing.

Broker codes are passed through from the Fabric broker, so new codes can appear over time. Treat an unknown code as a generic failure and still display error.message.

Embedded errors

In embedded mode, the host's error code and message are passed through unchanged. SDK-originated embedded codes include NO_PARENT_WINDOW (embedded auth requested outside an iframe), BRIDGE_TIMEOUT (the host did not respond), STATE_MISMATCH (the handoff response state did not match), and SESSION_NOT_ESTABLISHED (the handoff completed but no session was installed).

Direct token exchange errors

signInWithEntraToken() throws AuthError with these stable codes:

CodeMessage
INVALID_REQUESTA raw Entra access token is required.
INVALID_REQUESTAn absolute HTTPS backend URL is required.
EXCHANGE_NOT_ENABLEDExternal Entra exchange is not enabled.
AUTH_FAILEDEntra authentication failed.
INSUFFICIENT_PERMISSIONSItem Execute permission is required.
NOT_AVAILABLEExternal Entra exchange is not available.
TOKEN_EXCHANGE_FAILEDEntra token exchange failed.
INVALID_TOKEN_RESPONSEThe token exchange returned an invalid token response.

Dynamic claims errors

New in 2.0

When the app's dynamic claims function denies the user or fails, Fabric SSO sign-in and signInWithEntraToken() reject with SIGN_IN_DENIED, AUTH_CLAIMS_UNAVAILABLE, AUTH_CLAIMS_FAILED, or AUTH_CLAIMS_INVALID_OUTPUT. Fabric SSO reports the app's denial reason as error.message. signInWithEntraToken() reads only the x-ms-rayfin-error-code response header, never the body, so it reports the fixed message Sign-in was denied by the app. for a denial.

Troubleshooting

SymptomLikely causeFix
Sign-in fails with no visible messageThe app discards the sign-in error.Catch errors from ensureSignedInWithFabric() and render error.message.
Popup blockedCalled outside a synchronous user-gesture handler.Call ensureSignedInWithFabric() directly from a button onClick.
Session not persistingRayfinClient is configured for the wrong backend.Confirm baseUrl and publishableKey are correct.
Handoff times outThe popup handoff code was never received.Confirm returnOrigin matches the app's actual origin and is allowed by the backend.
initEmbeddedAuth() returns nullNo Fabric iframe or external embed host was detected, or embedded sign-in failed.Use popup sign-in for standalone pages; for iframes, verify the host path and check the console warning.
State mismatchReplayed or stale response.Retry the flow from scratch and investigate repeated failures.
Direct token exchange reports EXCHANGE_NOT_ENABLEDThe target app has not enabled external Entra exchange.Set services.auth.fabric.externalEntraExchange: true and apply runtime settings.

See Errors and troubleshooting for the full site-wide index.

Security notes

  • Popup and embedded Fabric SSO use PKCE S256 and state nonces.
  • The PKCE verifier stays in memory and is not persisted to localStorage.
  • Popup origin checks are advisory because the Fabric extension frame can differ from the portal origin; state plus PKCE are the enforcement boundary.
  • Normal Fabric embedded handoff does not set fabricPortalUrl as targetOrigin; external embed handoff uses the parent origin pinned by classification. Changed in 1.36
  • Direct token exchange never stores the supplied Entra token and sanitizes exchange errors.

Performance hints

New in 2.0

During sign-in, the SDK adds a <link rel="preconnect"> for the Rayfin API origin, unless the API is same-origin, so connection setup overlaps the user's sign-in. Sign-in also records rayfin:signin:* User Timing marks and measures — for example rayfin:signin:popup and rayfin:signin:total — which you can collect with a PerformanceObserver. Neither ever contains tokens or codes.

Runtime requirements

The package root and signInWithEntraToken() can run in Node.js without browser globals. Use memory-only or custom storage outside a browser.

The popup, iframe, and legacy callback helpers are browser-only. They depend on browser APIs such as window.open(), postMessage, BroadcastChannel, and window.location.

Something wrong on this page?Report an issueEdit this page

On this page