Skip to content

React + msal raises block_iframe_reload error #8685

Description

@emaborsa

Core Library

MSAL.js (@azure/msal-browser)

Core Library Version

5.6.3

Wrapper Library

MSAL React (@azure/msal-react)

Wrapper Library Version

None

Public or Confidential Client?

Public

Description

I am developing a react SPA and implementing msal:

"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.0",
"@azure/msal-browser": "^5.6.3",
"@azure/msal-react": "^5.2.1",
"@vitejs/plugin-react": "^6.0.2",
"swr": "^2.2.5",
"vite": "^8.0.7"

i tried to slightly change packages versions, did not help.
Switched to Axios, have same problem.
Tried a lot of AI, did not help.
Tested on Chrome and Edge.
the swr middleware worked on an old version at projects of my old company.

Error Message

Standard error:

ERROR Error: Uncaught (in promise): BrowserAuthError: block_iframe_reload: Request was blocked inside an iframe because MSAL detected an authentication response. For more visit: aka.ms/msaljs/browser-errors
BrowserAuthError: block_iframe_reload: Request was blocked inside an iframe because MSAL detected an authentication response. For more visit: aka.ms/msaljs/browser-errors

Adding redirectUri as mentioned in the docs:

Unsafe attempt to initiate navigation for frame with origin 'http://localhost:30730' from frame with URL 'https://login.microsoftonline.com/045c0c45-3c80-4b73-b52f-42f07d6207d4/oauth2/v2.0/authorize?client_id=02523c40-99cf-4e42-ae60-cf6c9970c2bf&scope=02523c40-99cf-4e42-ae60-cf6c9970c2bf%2F.default%20openid%20profile%20offline_access&redirect_uri=http%3A%2F%2Flocalhost%3A30730%2Fredirect&client-request-id=019f036a-11a7-7717-8d10-1027ced42247&response_mode=fragment&client_info=1&clidata=1&prompt=none&sid=00a96749-a377-1142-16af-0dd0a6b910c8&X-AnchorMailbox=Oid%3A871ae8c1-ae67-4d4b-bbc0-8ae0b871548d%40045c0c45-3c80-4b73-b52f-42f07d6207d4&nonce=019f036a-11ac-7eb0-86f0-5a8e7fd74708&state=eyJpZCI6IjAxOWYwMzZhLTExYWMtNzhmOC1hOTVmLTYzMDdkZThlMzU4ZiIsIm1ldGEiOnsiaW50ZXJhY3Rpb25UeXBlIjoic2lsZW50In19&x-client-SKU=msal.js.browser&x-client-VER=5.14.0&response_type=code&code_challenge=4MZOzNRENYe0SlK5pvcrGKH7pX3xu0yus_EJcxsjf4Y&code_challenge_method=S256'. The frame attempting navigation of the top-level window is sandboxed, but the flag of 'allow-top-navigation' or 'allow-top-navigation-by-user-activation' is not set.

MSAL Logs

No response

Network Trace (Preferrably Fiddler)

  • Sent
  • Pending

MSAL Configuration

import { BrowserCacheLocation, Configuration, PopupRequest, PublicClientApplication } from "@azure/msal-browser";

const CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxx";

export const msalConfig: Configuration = {
  auth: {
    clientId: CLIENT_ID,
    authority: "https://login.microsoftonline.com/zzzzzzzzzzzzzzzzzzzzzzzz",
    knownAuthorities: ["https://login.microsoftonline.com"],
    redirectUri: "/",
    postLogoutRedirectUri: "/",
  },
  cache: {
    cacheLocation: BrowserCacheLocation.LocalStorage,
  },
  system: {
    allowRedirectInIframe: false,
  },
};

export const msalInstance = new PublicClientApplication(msalConfig);
await msalInstance.initialize();

Relevant Code Snippets

swr middleware:

import { InteractionRequiredAuthError } from "@azure/msal-browser";
import { ConfiguredMiddleware } from "wretch";
import { msalApp } from "../context/authContext";

export type AuthOptions = {
  scopes: string[];
};

type AuthMiddleware = (options?: AuthOptions) => ConfiguredMiddleware;

export const authMiddleware: AuthMiddleware =
  ({ scopes } = { scopes: [] }) =>
  (next) =>
  (url, opts) => {
    let account = msalApp.getActiveAccount();

    // Handle case where no active account is set
    if (!account) {
      const allAccounts = msalApp.getAllAccounts();

      if (allAccounts.length === 0) {
        const msg = "No authenticated user account was found.";
        console.error(msg);
        throw Error(msg);
      } else if (allAccounts.length === 1) {
        // If there's only one account, set it as the active account
        account = allAccounts[0] ?? null;
        msalApp.setActiveAccount(account);
      } else {
        // If multiple accounts exist, prompt the user to select one
        console.warn("Multiple accounts detected. Prompting user to select one.");
        return msalApp
          .loginPopup({ prompt: "select_account", scopes })
          .then((response) => {
            if (response.account) {
              msalApp.setActiveAccount(response.account);
              return authMiddleware({ scopes })(next)(url, opts); // Retry with the selected account
            } else {
              throw Error("Account selection failed.");
            }
          })
          .catch((error) => {
            console.error("Error during account selection:", error);
            throw error;
          });
      }
    }

    // Proceed with the active account
    return msalApp
      .acquireTokenSilent({
        scopes,
        account: account ?? undefined,
      })
      .then((res) => {
        return next(url, {
          ...opts,
          headers: {
            ...opts["headers"],
            Authorization: `Bearer ${res.accessToken}`,
          },
        });
      })
      .catch((error) => {
        if (error instanceof InteractionRequiredAuthError) {
          msalApp.loginRedirect({ scopes });
        }
        return Promise.reject(error);
      });
  };


Axios interceptor:

apiClient.interceptors.request.use(async (config) => {
  const accounts = msalInstance.getAllAccounts();
  if (accounts.length === 0) return config;

  try {
    const result = await msalInstance.acquireTokenSilent({
      ...loginRequest,
      account: accounts[0],
      redirectUri: "http://localhost:30730/redirect",
    });
    config.headers.Authorization = `Bearer ${result.accessToken}`;
  } catch (error) {
    if (error instanceof InteractionRequiredAuthError) {
      await msalInstance.acquireTokenPopup(loginRequest);
    }
  }
  return config;
});

Reproduction Steps

Base React application. I reproduce it on all my new projects.

Expected Behavior

I expect that if the user is not logged in, it is redirected to MS login. IF logged in, silent get token.

Identity Provider

Entra ID (formerly Azure AD) / MSA

Browsers Affected (Select all that apply)

Chrome, Edge

Regression

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug-unconfirmedA reported bug that needs to be investigated and confirmedmsal-browserRelated to msal-browser packagemsal-reactRelated to @azure/msal-reactpublic-clientIssues regarding PublicClientApplicationsquestionCustomer is asking for a clarification, use case or information.

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions