admin管理员组

文章数量:1400336

I am trying to obtain an access token from Azure, but I am encountering an error when running my code:

Uncaught BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.

Here is my code setup for it

App.jsx

function App() {
const msalConfig = {
  auth: {
    clientId: '*******',
    authority: '/***********' 
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: true 
  }
}
  
  const pca = new PublicClientApplication(msalConfig)

  return (
    <div className="App">
      <MsalProvider instance={pca}>
          <BrowserRouter>
            <Routes>
              <Route element={<AppRoot />}>
                <Route path="/" element={<Prompt />} />
                <Route path="*" element={<Navigate to="/" />} />
              </Route>
            </Routes>
          </BrowserRouter>
      </MsalProvider>
    </div>
  )
}

Prompt.jsx

import { useAccount, useMsal } from '@azure/msal-react'
export const Prompt = () => {
  const { instance } = useMsal();
  useEffect(() => {
    login()
  }, []);

  const login = async () => {
    try {
      await instance.initialize();
      const response = await instance.loginPopup({
        scopes: ["api:********"]
      });

      console.log(response);
    }
    catch (err) {
      console.log(err)
    }
  };


  return (
    <div>Prompt</div>
  )
}

Can someone please assist me with it ?

I am trying to obtain an access token from Azure, but I am encountering an error when running my code:

Uncaught BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.

Here is my code setup for it

App.jsx

function App() {
const msalConfig = {
  auth: {
    clientId: '*******',
    authority: 'https://login.microsoftonline/***********' 
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: true 
  }
}
  
  const pca = new PublicClientApplication(msalConfig)

  return (
    <div className="App">
      <MsalProvider instance={pca}>
          <BrowserRouter>
            <Routes>
              <Route element={<AppRoot />}>
                <Route path="/" element={<Prompt />} />
                <Route path="*" element={<Navigate to="/" />} />
              </Route>
            </Routes>
          </BrowserRouter>
      </MsalProvider>
    </div>
  )
}

Prompt.jsx

import { useAccount, useMsal } from '@azure/msal-react'
export const Prompt = () => {
  const { instance } = useMsal();
  useEffect(() => {
    login()
  }, []);

  const login = async () => {
    try {
      await instance.initialize();
      const response = await instance.loginPopup({
        scopes: ["api:********"]
      });

      console.log(response);
    }
    catch (err) {
      console.log(err)
    }
  };


  return (
    <div>Prompt</div>
  )
}

Can someone please assist me with it ?

Share Improve this question asked Mar 24 at 12:42 RRR uzumakiRRR uzumaki 1,3284 gold badges28 silver badges63 bronze badges 1
  • Could you confirm whether you exposed any API and enabled public client flow option? Please include your Authentication tab image of your app registration. – Sridevi Commented Mar 24 at 12:54
Add a comment  | 

1 Answer 1

Reset to default 0

The error occurred because MSAL was used before it was fully initialized. To fix this, remove the initialize() call, ensure MSAL is ready in App.jsx, and let the user trigger login with a button instead of using useEffect.

Initially, I registered one application and added redirect URI as http://localhost:3000 in SPA platform:

Now, I exposed one API in it with scope named user_impersonation as below:

In my case, I used below code files that worked and gave access token successfully after user login:

src/components/App.jsx:

import React, { useEffect, useState } from 'react';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { msalConfig } from '../config/authConfig';
import Prompt from './Prompt';

// Initialize MSAL instance
const pca = new PublicClientApplication(msalConfig);

function App() {
    const [isMsalInitialized, setIsMsalInitialized] = useState(false);

    useEffect(() => {
        pca.initialize()
            .then(() => setIsMsalInitialized(true))
            .catch(error => console.error("MSAL initialization failed:", error));
    }, []);

    if (!isMsalInitialized) {
        return <p>Initializing authentication...</p>;
    }

    return (
        <MsalProvider instance={pca}>
            <BrowserRouter>
                <div>
                    <h1>Welcome to MSAL React App</h1>
                    <Routes>
                        <Route element={<Outlet />}>
                            <Route path="/" element={<Prompt />} />
                            <Route path="*" element={<Navigate to="/" />} />
                        </Route>
                    </Routes>
                </div>
            </BrowserRouter>
        </MsalProvider>
    );
}

export default App;

src/components/Prompt.jsx:

import React, { useState, useCallback } from 'react';
import { useMsal } from '@azure/msal-react';
import { loginRequest } from '../config/authConfig';

const Prompt = () => {
    const { instance } = useMsal();
    const [accessToken, setAccessToken] = useState('');
    const [user, setUser] = useState(null);

    const login = useCallback(async () => {
        try {
            const loginResponse = await instance.loginPopup(loginRequest);
            instance.setActiveAccount(loginResponse.account);
            setUser(loginResponse.account);

            const tokenResponse = await instance.acquireTokenSilent(loginRequest);
            setAccessToken(tokenResponse.accessToken);
        } catch (error) {
            console.error("Login failed:", error);
        }
    }, [instance]);

    const logout = () => {
        instance.logoutPopup();
        setUser(null);
        setAccessToken('');
    };

    return (
        <div>
            <h1>MSAL Authentication</h1>
            {!user ? (
                <button onClick={login}>Login with Microsoft</button>
            ) : (
                <div>
                    <h2>Welcome, {user.name}!</h2>
                    <button onClick={logout}>Logout</button>

                    {accessToken && (
                        <div>
                            <h3>Access Token:</h3>
                            <p>{accessToken}</p>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default Prompt;

src/config/authConfig.js:

export const msalConfig = {
    auth: {
        clientId: "appId", // Replace with your App Registration Client ID
        authority: "https://login.microsoftonline/tenantId", // Replace with your Tenant ID
        redirectUri: "http://localhost:3000",
    },
    cache: {
        cacheLocation: "localStorage", 
        storeAuthStateInCookie: true,
    }
};

// Scopes required for API access
export const loginRequest = {
    scopes: ["api://0f493dbb-xxxxxxxxxxxxx/user_impersonation"], // Replace with your API scope
};

Response:

To confirm that, I decoded this token in jwt.ms website and got below claims:

本文标签: reactjsUncaught BrowserAuthError uninitializedpublicclientapplicationStack Overflow