Search code examples
azure-ad-b2cazure-ad-msalmsal.jsmsal-react

MSAL 2.0 Redirect User to Login Screen Fast


I use below libraries: "@azure/msal-browser": "^2.16.0", "@azure/msal-react": "^1.0.1",

I need to redirect the user to login screen without user being able to see any content. How would I be able to do that?

Currently, I have this:

export default function Main() {
  const msalInstance = new PublicClientApplication(msalConfig);
  useEffect(() => {
    msalInstance
      .handleRedirectPromise()
      .then((s) => {
        if (s === null) msalInstance.loginRedirect(loginRequest); // not logged in
        else console.log(s); // logged in
      })
      .catch((a: any) => {
        console.log("err");
        console.log(a);
      });
  }, []);
  return <App instance={msalInstance} />;
}

But, it loads the app for a second then does the redirection.

Solution

  • In order to achieve that specific behavior, there are two options:

    1. Delay rendering your app until the user is confirmed to be logged in (they will be redirected to authenticate before you render your app).
    2. Handle this on the server side by redirecting to the login interaction before the app is rendered (which would involve a solution other than msal-react).

    Here is some documentation on the MSAL AuthenticationTemplate, which may be of some help in determining what the right way to use MSAL React would be in this case.

    As a final note, it's not recommended that you initialize the PublicClientApplication inside a React component. Please review the Getting Started documentation and the react-router-sample for more guidance on how to initialize MSAL in your application.