msal-react/browser doesn't initiate login when deployed, works fine locally

148 Views Asked by At

I have a React app that uses msal-browser & msal-react. I begin to experience issues when my app is deployed (via Azure Web App, Azure Static Web App, and the Azure Static Web App CLI locally). This works fine locally with npm run start however.

The issue is instance.loginPopup() and instance.loginRedirect() don't initiate any popups or redirects, and instead give these errors:

enter image description here

enter image description here

The cookies have a value for msal.interaction.status which is always undefined

enter image description here

I've been following the MS samples closely, and am unsure why this is only happening when deployed.

Here is my code:

Index.tsx

const msalInstance = new PublicClientApplication(msalConfig);
  msalInstance.initialize().then(() => {
    console.log('Initialised!');

    if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) {
      msalInstance.setActiveAccount(msalInstance.getAllAccounts()[0]);
    } 

    msalInstance.enableAccountStorageEvents();

    msalInstance.addEventCallback((event: any) => {
      if (event.eventType === EventType.LOGIN_SUCCESS
        ||
        event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS
        ||
        event.eventType === EventType.SSO_SILENT_SUCCESS
      ) {
        const account = event.payload.account;
        msalInstance.setActiveAccount(account);
      }
    });
  })
  .catch((err) => {
    console.log('Error');
    console.log(err);
  })

AuthConfig.tsx

export const msalConfig: Configuration = {
  auth: {
    clientId: process.env.REACT_APP_CLIENT_ID as string,
    authority: b2cPolicies.authorities.signUpSignIn.authority,
    knownAuthorities: [b2cPolicies.authorityDomain],
    redirectUri: process.env.REACT_APP_REDIRECT_URI,
    postLogoutRedirectUri: '/',
    navigateToLoginRequestUrl: false
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: isIE || isEdge || isFirefox
  },
  system: {
    allowNativeBroker: false, 
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        if (containsPii) {
          return;
        }
        switch (level) {
          case LogLevel.Error:
            console.error(message);
            return;
          case LogLevel.Info:
            console.info(message);
            return;
          case LogLevel.Verbose:
            console.debug(message);
            return;
          case LogLevel.Warning:
            console.warn(message);
            return;
          default:
            return;
        }
      }
    }
  }
};

App.tsx

function App({ msalInstance }: { msalInstance: PublicClientApplication }) {
  return (
    <MsalProvider instance={msalInstance}>
      <SignInSignOut />
      <div>
        Home
      </div>
    </MsalProvider>
  );
}

SignIn.tsx

const SignIn = () => {
  const { instance } = useMsal();

  const logIn = () => {
    instance.loginRedirect();
  }

  return (
    <button onClick={logIn}>Sign In</button>
  )
};
1

There are 1 best solutions below

0
Dasari Kamali On

I made some changes to your code and successfully signed in with Azure B2C tenant locally and in the Azure web app.

Code:

Note : Replace the localhost URL with the web app URL in redirectUri before deployment. https://<webapp_name>.azurewebsites.net/

msal/AuthConfig.tsx :

import { Configuration, LogLevel } from '@azure/msal-browser';

export const msalConfig: Configuration = {
  auth: {
    clientId: "<client_ID>" as string,
    authority: 'https://<b2c-tenant>.b2clogin.com/<your-b2c-tenant>.onmicrosoft.com/<policy-name>', 
    knownAuthorities: ['https://<b2c-tenant>.b2clogin.com/<your-b2c-tenant>.onmicrosoft.com/<policy-name>'], 
    redirectUri: "http://localhost:3000/",  //https://<webapp_name>.azurewebsites.net/
    postLogoutRedirectUri: '/',
    navigateToLoginRequestUrl: false,
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: false,
  },
  system: {
    allowNativeBroker: false,
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        if (containsPii) {
          return;
        }
        switch (level) {
          case LogLevel.Error:
            console.error(message);
            return;
          case LogLevel.Info:
            console.info(message);
            return;
          case LogLevel.Verbose:
            console.debug(message);
            return;
          case LogLevel.Warning:
            console.warn(message);
            return;
          default:
            return;
        }
      },
    },
  },
};

msalInstance.ts :

import { PublicClientApplication, Configuration, LogLevel, EventType } from '@azure/msal-browser';
import { msalConfig } from './msal/AuthConfig';

const msalInstance = new PublicClientApplication(msalConfig);
msalInstance.initialize()
  .then(() => {
    console.log('Initialized!');

    if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) {
      msalInstance.setActiveAccount(msalInstance.getAllAccounts()[0]);
    }

    msalInstance.enableAccountStorageEvents();
    msalInstance.addEventCallback((event: any) => {
      if (
        event.eventType === EventType.LOGIN_SUCCESS ||
        event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS ||
        event.eventType === EventType.SSO_SILENT_SUCCESS
      ) {
        const account = event.payload.account;
        msalInstance.setActiveAccount(account);
      }
    });
  })
  .catch((err) => {
    console.error('Error during initialization');
    console.error(err);
  });
export default msalInstance;

components/SignIn.tsx :

import React from 'react';
import { useMsal } from '@azure/msal-react';

const SignIn: React.FC = () => {
  const { instance } = useMsal();
  const logIn = () => {
    instance.loginRedirect();
  };

  return (
    <button onClick={logIn}>Sign In</button>
  );
};
export default SignIn;

components/App.tsx :

import React from 'react';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import SignIn from './SignIn';
import { msalConfig } from '../msal/AuthConfig';

const msalInstance = new PublicClientApplication(msalConfig);
const App: React.FC = () => {
  return (
    <MsalProvider instance={msalInstance}>
      <SignIn />
      <div>
        Home
      </div>
    </MsalProvider>
  );
};
export default App;

src/index.tsx :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

I added the URLs below to the app's Redirect URI as follows:

http://localhost:3000/
https://<webapp_name>.azurewebsites.net/

enter image description here

Output :

It ran successfully, as shown below:

enter image description here

I got the output below with the above output URL in the browser. I clicked the Sign In button to sign in, as shown below:

enter image description here

I successfully signed in with my email ID and password, as shown below.

enter image description here

I deployed my build folder to the Azure web app, as shown below:

enter image description here

It deployed successfully, as shown below.

enter image description here

I got the page below with the web app URL. I clicked the Sign In button to sign in, as shown below:

enter image description here

I successfully signed in with my email ID and password, as shown below.

enter image description here