Factory functions for msal angular are executed before the APP_INITIALIZER

Discussão em 'Angular' iniciado por kunal, Dezembro 4, 2024.

  1. kunal

    kunal Guest

    I am authenticating a user through Microsoft Azure AD in my Angular application(SPA) and I want to provide clientId dynamically in IPublicClientApplication. To achieve this I am calling backend endpoing which return client Id, which I store globally and trying to use in client_id field of auth object. But I am getting globalClientId as undefined but when I check in the initializeApp function globalClientId has expected value. The issue seems to be that the MSAL (Azure AD) providers are executing before the APP_INITIALIZER function completes, which results in the clientId being unavailable at the time the MSAL configuration is initialized.

    let globalClientId = '';

    export function initializeApp(authenticationService: AuthenticationService) {
    return () => authenticationService.loadAppConfig().then(clientData => {
    globalClientId = clientData.config.clientId;
    }).catch(err => {
    console.error('Failed to load app configuration:', err);
    });
    }

    export function MSALInstanceFactory(): IPublicClientApplication {
    return new PublicClientApplication({
    auth: {
    clientId: globalClientId,
    authority: globalCloudInstance,
    redirectUri: globalRedirectUri,
    postLogoutRedirectUri: '/'
    },
    cache: {
    cacheLocation: BrowserCacheLocation.LocalStorage
    },
    system: {
    allowNativeBroker: false,
    loggerOptions: {
    loggerCallback,
    logLevel: LogLevel.Info,
    piiLoggingEnabled: false
    }
    }
    });
    }



    I found the workaround with the help of following post and it has solved my issue, but I am searching for more appropriate solution Angular (v15) providers for Azure AD are executed before the APP_INITIALIZER promise is resolved

    (async () => {
    const data = await fetch('backend_url), {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({
    someid : someid
    })
    });
    if (data.ok) {
    const responseData = await data.json();
    appData.clientId = responseData.auth.client_id;
    } else {
    console.error('Failed to fetch app data:', data.statusText);
    }

    platformBrowserDynamic().bootstrapModule(AppModule).then(ref =>{
    })
    .catch(err => console.error(err));
    })();

    Continue reading...

Compartilhe esta Página