我的解决方案是@azure/msal-browser
在 Microsoft Graph Toolkit ( @microsoft/mgt-element
) 和@azure/msal-react
库中使用相同的实例,如下所示:
// MSAL React
import { MsalProvider as MsalReactProvider } from "@azure/msal-react";
import { Configuration, PublicClientApplication } from "@azure/msal-browser";
// Microsoft Graph Toolkit
import { Providers as MGT_Providers } from '@microsoft/mgt-element';
import { Msal2Provider as MGT_Msal2Provider } from '@microsoft/mgt-msal2-provider';
// Your app
import App from './App';
// MSAL configuration
const configuration: Configuration = {
... MSAL Browser config
};
// Instantiate MSAL-Browser
const pca = new PublicClientApplication(configuration);
// instantiate the global provider for MGT
MGT_Providers.globalProvider = new MGT_Msal2Provider({ publicClientApplication: pca });
ReactDOM.render(
<MsalReactProvider instance={pca}>
<App />
</MsalReactProvider> document.getElementById('root')
);
并在应用程序组件中进行一些引导以保持日志状态同步:
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
import { Providers as MGT_Providers, ProviderState } from '@microsoft/mgt-element';
export function App() {
const isAuthenticated = useIsAuthenticated();
const { inProgress } = useMsal();
useEffect(() => {
console.log("isAuthenticated, inProgress: ", [isAuthenticated, inProgress], [typeof isAuthenticated, typeof inProgress])
MGT_Providers.globalProvider.setState(inProgress !== "none" ? ProviderState.Loading : (isAuthenticated ? ProviderState.SignedIn : ProviderState.SignedOut))
}, [isAuthenticated, inProgress])
...
}