Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(sdk): skip first /auth/sso request when jwtProviderUri is passed (#66120)

Nicolò Pretto02f2d128f7eb
diff --git a/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx
new file mode 100644
index 00000000000..f76819cdeeb
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx
@@ -0,0 +1,80 @@
+import { InteractiveQuestion } from "@metabase/embedding-sdk-react";
+
+import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing";
+import {
+ AUTH_PROVIDER_URL,
+ METABASE_INSTANCE_URL,
+} from "e2e/support/helpers/embedding-sdk-helpers/constants";
+import {
+ mockAuthProviderAndJwtSignIn,
+ signInAsAdminAndEnableEmbeddingSdk,
+} from "e2e/support/helpers/embedding-sdk-testing";
+
+describe("scenarios > embedding-sdk > loading-performance", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ // Intercept SSO discovery request (without jwt parameter)
+ cy.intercept("GET", /\/auth\/sso(\?preferred_method=\w+)?$/).as(
+ "authSsoDiscovery",
+ );
+ // Intercept token exchange request (with jwt parameter)
+ cy.intercept("GET", /\/auth\/sso\?.*jwt=/).as("authSsoTokenExchange");
+ cy.intercept("GET", "/api/user/current").as("getCurrentUser");
+ cy.intercept("GET", "/api/session/properties").as("getSessionProperties");
+ });
+
+ describe("Baseline: when jwtProviderUri is not provided", () => {
+ it("should make SSO discovery request, then token exchange", () => {
+ mountSdkContent(<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />, {
+ sdkProviderProps: {
+ authConfig: {
+ metabaseInstanceUrl: METABASE_INSTANCE_URL,
+ },
+ },
+ });
+
+ // Verify question renders
+ getSdkRoot().within(() => {
+ cy.findByText("Orders").should("exist");
+ cy.findByTestId("visualization-root").should("be.visible");
+ });
+
+ // Baseline: discovery + token exchange
+ cy.get("@authSsoDiscovery.all").should("have.length", 1);
+ cy.get("@authSsoTokenExchange.all").should("have.length", 1);
+ cy.get("@getCurrentUser.all").should("have.length", 1);
+ cy.get("@getSessionProperties.all").should("have.length", 1);
+ });
+ });
+
+ describe("when jwtProviderUri is provided", () => {
+ it("should skip the initial /auth/sso request", () => {
+ mountSdkContent(<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />, {
+ sdkProviderProps: {
+ authConfig: {
+ metabaseInstanceUrl: METABASE_INSTANCE_URL,
+ preferredAuthMethod: "jwt",
+ jwtProviderUri: AUTH_PROVIDER_URL,
+ },
+ },
+ });
+
+ // Verify question renders
+ getSdkRoot().within(() => {
+ cy.findByText("Orders").should("exist");
+ cy.findByTestId("visualization-root").should("be.visible");
+ });
+
+ // Optimized: no discovery, only token exchange
+ cy.get("@authSsoDiscovery.all").should("have.length", 0);
+ cy.get("@authSsoTokenExchange.all").should("have.length", 1);
+ cy.get("@getCurrentUser.all").should("have.length", 1);
+ cy.get("@getSessionProperties.all").should("have.length", 1);
+ });
+ });
+});
diff --git a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx
index 6b491e03431..d3fe05afb03 100644
--- a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx
@@ -38,25 +38,10 @@ describe("scenarios > embedding-sdk > requests", () => {
});
});
- beforeEach(() => {
+ it("properly performs session token refresh request when multiple data requests are triggered at the same time", () => {
cy.clock(Date.now());
- });
- afterEach(() => {
- cy.clock().then((clock) => clock.restore());
- });
-
- it("properly performs session token refresh request when multiple data requests are triggered at the same time", () => {
- let datasetCount = 0;
- cy.intercept("POST", "/api/dataset", (req) => {
- datasetCount++;
- // eslint-disable-next-line no-console
- console.log(
- `Dataset request #${datasetCount}`,
- req.headers["x-metabase-session"],
- );
- req.continue();
- }).as("dataset");
+ cy.intercept("POST", "/api/dataset").as("dataset");
const sessionIds: string[] = [];
diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
index 4158e3a9787..3d9bfcf6b3d 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
@@ -43,14 +43,16 @@ let refreshTokenPromise: ReturnType<
// Side effect happening here.
PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
- {
- metabaseInstanceUrl,
- preferredAuthMethod,
- apiKey,
- isLocalHost,
- }: MetabaseAuthConfig & { isLocalHost?: boolean },
+ authConfig: MetabaseAuthConfig & { isLocalHost?: boolean },
{ dispatch }: { dispatch: SdkDispatch },
) => {
+ const { metabaseInstanceUrl, preferredAuthMethod, apiKey, isLocalHost } =
+ authConfig;
+
+ // This is needed because of how MetabaseAuthConfig is typed
+ const jwtProviderUri =
+ "jwtProviderUri" in authConfig ? authConfig.jwtProviderUri : undefined;
+
// remove any stale tokens that might be there from a previous session=
samlTokenStorage.remove();
@@ -72,6 +74,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
getOrRefreshSession({
metabaseInstanceUrl,
preferredAuthMethod,
+ jwtProviderUri,
}),
).unwrap();
if (session?.id) {
@@ -84,6 +87,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
getOrRefreshSession({
metabaseInstanceUrl,
preferredAuthMethod,
+ jwtProviderUri,
}),
).unwrap();
} catch (e) {
@@ -119,7 +123,12 @@ const refreshTokenImpl = async (
{
metabaseInstanceUrl,
preferredAuthMethod,
- }: Pick<MetabaseAuthConfig, "metabaseInstanceUrl" | "preferredAuthMethod">,
+ jwtProviderUri,
+ }: {
+ metabaseInstanceUrl: string;
+ preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];
+ jwtProviderUri?: string;
+ },
{ getState }: { getState: () => unknown },
): Promise<MetabaseEmbeddingSessionToken | null> => {
const state = getState() as SdkStoreState;
@@ -133,6 +142,7 @@ const refreshTokenImpl = async (
const session = await getRefreshToken({
metabaseInstanceUrl,
preferredAuthMethod,
+ jwtProviderUri,
fetchRequestToken: customGetRefreshToken,
});
validateSession(session);
@@ -152,10 +162,11 @@ PLUGIN_EMBEDDING_SDK_AUTH.refreshTokenAsync = refreshTokenImpl;
export const getOrRefreshSession = createAsyncThunk(
GET_OR_REFRESH_SESSION,
async (
- authConfig: Pick<
- MetabaseAuthConfig,
- "metabaseInstanceUrl" | "preferredAuthMethod"
- >,
+ authConfig: {
+ metabaseInstanceUrl: string;
+ preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];
+ jwtProviderUri?: string;
+ },
{ dispatch, getState },
) => {
// necessary to ensure that we don't use a popup every time the user
@@ -193,15 +204,23 @@ export const getOrRefreshSession = createAsyncThunk(
const getRefreshToken = async ({
metabaseInstanceUrl,
preferredAuthMethod,
+ jwtProviderUri,
fetchRequestToken: customGetRequestToken,
-}: Pick<
- MetabaseAuthConfig,
- "metabaseInstanceUrl" | "fetchRequestToken" | "preferredAuthMethod"
->) => {
- const urlResponseJson = await connectToInstanceAuthSso(metabaseInstanceUrl, {
- preferredAuthMethod,
- headers: getSdkRequestHeaders(),
- });
+}: {
+ metabaseInstanceUrl: string;
+ preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];
+ jwtProviderUri?: string;
+ fetchRequestToken?: MetabaseAuthConfig["fetchRequestToken"];
+}) => {
+ const shouldSkipSsoDiscovery = jwtProviderUri !== undefined;
+
+ const urlResponseJson = shouldSkipSsoDiscovery
+ ? { method: "jwt", url: jwtProviderUri }
+ : await connectToInstanceAuthSso(metabaseInstanceUrl, {
+ preferredAuthMethod,
+ headers: getSdkRequestHeaders(),
+ });
+
const { method, url: responseUrl, hash } = urlResponseJson || {};
if (method === "saml") {
const token = await openSamlLoginPopup(responseUrl);
@@ -209,7 +228,7 @@ const getRefreshToken = async ({
return token;
}
- if (method === "jwt") {
+ if (method === "jwt" && responseUrl) {
return jwtDefaultRefreshTokenFunction(
responseUrl,
metabaseInstanceUrl,
diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
index 27a6715718f..4eaa81daaa5 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
@@ -29,10 +29,25 @@ const setup = ({
locale,
}: Pick<MetabaseProviderProps, "authConfig" | "locale">) => {
setupMockJwtEndpoints();
+
+ const getFirstSsoDiscoveryCall = () => {
+ // This is `/auth/sso` or `auth/sso?preferred_method=...`
+ // that returns the method (jwt/saml) and the url of the sso provider
+ // `auth/sso?jwt=...` is the second call and should be excluded from this
+ return fetchMock.callHistory
+ .calls()
+ .filter(
+ (call) =>
+ new URL(call.url).pathname === "/auth/sso" &&
+ !new URL(call.url).searchParams.has("jwt"),
+ );
+ };
+
return {
...baseSetup({ authConfig, locale }),
getLastAuthProviderApiCall: () =>
fetchMock.callHistory.lastCall(`${MOCK_JWT_PROVIDER_URI}?response=json`),
+ getFirstSsoDiscoveryCall,
};
};
@@ -46,7 +61,7 @@ describe("Auth Flow - JWT", () => {
metabaseInstanceUrl: MOCK_INSTANCE_URL,
});
- const { rerender } = setup({ authConfig });
+ const { rerender, getFirstSsoDiscoveryCall } = setup({ authConfig });
await waitForLoaderToBeRemoved();
expect(
@@ -65,6 +80,8 @@ describe("Auth Flow - JWT", () => {
fetchMock.callHistory.calls(`${MOCK_JWT_PROVIDER_URI}?response=json`),
).toHaveLength(1);
+ expect(getFirstSsoDiscoveryCall()).toHaveLength(1);
+
const loader = screen.queryByTestId("loading-indicator");
expect(loader).not.toBeInTheDocument();
@@ -104,6 +121,21 @@ describe("Auth Flow - JWT", () => {
);
});
+ it("should skip the initial /auth/sso request when jwtProviderUri is provided", async () => {
+ const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: MOCK_INSTANCE_URL,
+ jwtProviderUri: MOCK_JWT_PROVIDER_URI,
+ });
+
+ const { getLastAuthProviderApiCall, getFirstSsoDiscoveryCall } = setup({
+ authConfig,
+ });
+
+ await waitForRequest(() => getLastAuthProviderApiCall());
+
+ expect(getFirstSsoDiscoveryCall()).toHaveLength(0);
+ });
+
it("should use `fetchRequestToken` if provided", async () => {
const customFetchFunction = jest.fn().mockImplementation(() => ({
jwt: MOCK_VALID_JWT_RESPONSE,
@@ -115,7 +147,11 @@ describe("Auth Flow - JWT", () => {
fetchRequestToken: customFetchFunction,
});
- const { getLastCardQueryApiCall, getLastUserApiCall } = setup({
+ const {
+ getLastCardQueryApiCall,
+ getLastUserApiCall,
+ getFirstSsoDiscoveryCall,
+ } = setup({
authConfig,
});
@@ -123,6 +159,8 @@ describe("Auth Flow - JWT", () => {
expect(customFetchFunction).toHaveBeenCalled();
+ expect(getFirstSsoDiscoveryCall()).toHaveLength(1);
+
expect(getLastUserApiCall()?.options.headers).toHaveProperty(
"x-metabase-session",
MOCK_SESSION_TOKEN_ID,
diff --git a/frontend/src/embedding-sdk-bundle/store/auth/auth.ts b/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
index 9720efec66c..1afbbd3c64e 100644
--- a/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
+++ b/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
@@ -21,23 +21,10 @@ export const PLUGIN_EMBEDDING_SDK_AUTH = {
export const initAuth = createAsyncThunk(
"sdk/token/INIT_AUTH",
async (
- {
- metabaseInstanceUrl,
- preferredAuthMethod,
- apiKey,
- isLocalHost,
- }: MetabaseAuthConfig & { isLocalHost?: boolean },
+ authConfig: MetabaseAuthConfig & { isLocalHost?: boolean },
{ dispatch },
) => {
- return await PLUGIN_EMBEDDING_SDK_AUTH.initAuth(
- {
- metabaseInstanceUrl,
- preferredAuthMethod,
- apiKey,
- isLocalHost,
- },
- { dispatch },
- );
+ return await PLUGIN_EMBEDDING_SDK_AUTH.initAuth(authConfig, { dispatch });
},
);
@@ -47,13 +34,19 @@ export const refreshTokenAsync = createAsyncThunk(
{
metabaseInstanceUrl,
preferredAuthMethod,
- }: Pick<MetabaseAuthConfig, "metabaseInstanceUrl" | "preferredAuthMethod">,
+ jwtProviderUri,
+ }: {
+ metabaseInstanceUrl: string;
+ preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];
+ jwtProviderUri?: string;
+ },
{ getState },
): Promise<MetabaseEmbeddingSessionToken | null> => {
return await PLUGIN_EMBEDDING_SDK_AUTH.refreshTokenAsync(
{
metabaseInstanceUrl,
preferredAuthMethod,
+ jwtProviderUri,
},
{ getState },
);
diff --git a/frontend/src/embedding-sdk-bundle/types/auth-config.ts b/frontend/src/embedding-sdk-bundle/types/auth-config.ts
index edba7cacc70..23d85ad54a3 100644
--- a/frontend/src/embedding-sdk-bundle/types/auth-config.ts
+++ b/frontend/src/embedding-sdk-bundle/types/auth-config.ts
@@ -18,6 +18,11 @@ export type MetabaseAuthConfigWithJwt = BaseMetabaseAuthConfig & {
*/
preferredAuthMethod?: "jwt";
+ /**
+ * Uri of the jwt provider. If provided the sdk will use jwt and will skip the first `/auth/sso` discovery request.
+ */
+ jwtProviderUri?: string;
+
/**
* Specifies a function to fetch the refresh token.
* The refresh token should be in the format of {@link UserBackendJwtResponse}