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 |1 Answer
Reset to default 0The 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
版权声明:本文标题:reactjs - Uncaught BrowserAuthError: uninitialized_public_client_application - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744251367a2597263.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Authentication
tab image of your app registration. – Sridevi Commented Mar 24 at 12:54