Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

You must call and await the initialize function before attempting to call any other MSAL API #918

Closed
howard2019007 opened this issue Apr 5, 2024 · 10 comments

Comments

@howard2019007
Copy link

ERROR
uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API. For more visit: aka.ms/msaljs/browser-errors
BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API. For more visit: aka.ms/msaljs/browser-errors
at createBrowserAuthError (http://localhost:3000/static/js/bundle.js:190000:10)
at blockAPICallsBeforeInitialize (http://localhost:3000/static/js/bundle.js:194490:94)
at StandardController.handleRedirectPromise (http://localhost:3000/static/js/bundle.js:188079:92)
at PublicClientApplication.handleRedirectPromise (http://localhost:3000/static/js/bundle.js:185227:28)
at http://localhost:3000/static/js/bundle.js:14614:27

@s-o-w
Copy link

s-o-w commented Apr 10, 2024

I'm also having this error/issue. Not sure what's going on, the app behaves all the way through the authentication step(s), but when returning back to the app, prior to calling for chats, get the error reported above. Have tried in incognito/inprivate, still the same

@kill136
Copy link

kill136 commented Apr 11, 2024

me too !

BrowserAuthError.ts:351 Uncaught (in promise) BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API. For more visit: aka.ms/msaljs/browser-errors
at createBrowserAuthError (BrowserAuthError.ts:351:1)
at blockAPICallsBeforeInitialize (BrowserUtils.ts:136:1)
at StandardController.handleRedirectPromise (StandardController.ts:333:1)
at PublicClientApplication.handleRedirectPromise (PublicClientApplication.ts:259:1)
at index.tsx:44:1

@Riya-Chaudhary-dev
Copy link

I'm getting the same error when I start the app!

@s-o-w
Copy link

s-o-w commented Apr 15, 2024

Little more information from the logs. I'm not sure what's going on here - not a REACT programmer so I can't really tell where it's failing, but it looks like it's not setting the token in localstorage, but then expecting to find it there. This is on localhost, testing with a properly configured frontend/backend app (I know that works, it will go through the flow, just not complete once it returns back to the client).

sk-chatbot:authHelper info: +1ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 sk-chatbot:authHelper info: +0ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 sk-chatbot:authHelper info: +1ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-react@2.0.14 : Info - MsalProvider - msal:handleRedirectStart results in setting inProgress from startup to handleRedirect common.js:113 sk-chatbot:authHelper info: +0ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 sk-chatbot:authHelper info: +0ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-react@2.0.14 : Info - MsalProvider - msal:handleRedirectEnd results in setting inProgress from handleRedirect to none common.js:113 sk-chatbot:authHelper info: +0ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 sk-chatbot:authHelper info: +1ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 sk-chatbot:authHelper info: +0ms [Mon, 15 Apr 2024 13:50:13 GMT] : [] : @azure/msal-common@14.8.1 : Info - CacheManager:getIdToken - Returning ID token common.js:113 [2024-04-15T13:50:13.267Z] Information: Using HubProtocol 'json'. Utils.ts:191 SignalR connection established signalRHubConnection.ts:108 sk-chatbot:authHelper info: +3s [Mon, 15 Apr 2024 13:50:16 GMT] : [] : @azure/msal-browser@3.11.1 : Info - initialize has already been called, exiting early. common.js:113 sk-chatbot:authHelper info: +3s [Mon, 15 Apr 2024 13:50:19 GMT] : [] : @azure/msal-browser@3.11.1 : Info - initialize has already been called, exiting early. common.js:113 sk-chatbot:authHelper info: +3s [Mon, 15 Apr 2024 13:50:22 GMT] : [] : @azure/msal-browser@3.11.1 : Info - initialize has already been called, exiting early. common.js:113

@kbrkrgz10
Copy link

I'm getting the same error when configuring AzureAD authentication. But if you want to work without AzureAD, you can remove the frontend and authentication configuration from appsettings.development.json. You can work with guest user.

@kbrkrgz10
Copy link

kbrkrgz10 commented Apr 17, 2024

Hello fixed this problem with the below code in webapp\src\index.tsx file.
msalInstance.handleRedirectPromise().then((response) -> response came null so an error occurred. I added else condition and got active account.

image

Reference links:

@howard2019007
Copy link
Author

@kbrkrgz10 感谢分享解决了我的问题,以下是我修改后的源码
`import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import ReactDOM from 'react-dom/client';
import { Provider as ReduxProvider } from 'react-redux';
import App from './App';
import { Constants } from './Constants';
import './index.css';
import { AuthConfig, AuthHelper } from './libs/auth/AuthHelper';
import { store } from './redux/app/store';

import React from 'react';
import { BackendServiceUrl } from './libs/services/BaseService';
import { setAuthConfig } from './redux/features/app/appSlice';

if (!localStorage.getItem('debug')) {
localStorage.setItem('debug', ${Constants.debug.root}:*);
}

let container: HTMLElement | null = null;
let root: ReactDOM.Root | undefined = undefined;
let msalInstance: PublicClientApplication | undefined;

document.addEventListener('DOMContentLoaded', () => {
if (!container) {
container = document.getElementById('root');
if (!container) {
throw new Error('Could not find root element');
}
root = ReactDOM.createRoot(container);

    renderApp();
}

});

export function renderApp() {
fetch(new URL('authConfig', BackendServiceUrl))
.then((response) => (response.ok ? (response.json() as Promise) : Promise.reject()))
.then(async (authConfig) => {
store.dispatch(setAuthConfig(authConfig));

        if (AuthHelper.isAuthAAD()) {
            if (!msalInstance) {
                msalInstance = new PublicClientApplication(AuthHelper.getMsalConfig(authConfig));
                debugger;
                await msalInstance.initialize();
                await msalInstance
                    .handleRedirectPromise()
                    .then((response) => {
                        if (response) {
                            msalInstance?.setActiveAccount(response.account);
                        } else {
                            const activeAccount = msalInstance?.getAllAccounts()[0];
                            if (activeAccount) {
                                msalInstance?.setActiveAccount(activeAccount);
                            }
                        }
                    })
                    .catch((e) => {
                        console.log('handleRedirectPromise: ', e);
                    });
            }

            // render with the MsalProvider if AAD is enabled
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            root!.render(
                <React.StrictMode>
                    <ReduxProvider store={store}>
                        <MsalProvider instance={msalInstance}>
                            <App />
                        </MsalProvider>
                    </ReduxProvider>
                </React.StrictMode>,
            );
        }
    })
    .catch(() => {
        store.dispatch(setAuthConfig(undefined));
    });

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
root!.render(
    <React.StrictMode>
        <ReduxProvider store={store}>
            <App />
        </ReduxProvider>
    </React.StrictMode>,
);

}
`

@s-o-w
Copy link

s-o-w commented Apr 17, 2024

fixed it on my end using the code from @kbrkrgz10 above, thank you so much!

@maximuskh
Copy link

I still get this error in the last code I got from main and even adding what recommended by @kbrkrgz10 does not fixed it for me

@glahaye
Copy link
Collaborator

glahaye commented Jun 13, 2024

That has been fixed by #969

@glahaye glahaye closed this as completed Jun 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants