我的解决方案是在Microsoft Graph Toolkit (@microsoft/mgt-element
)和@azure/msal-react
库中使用相同的@azure/msal-browser
实例,如下所示:
// 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])
...
}
import {Providers, SimpleProvider, ProviderState} from '@microsoft/mgt-element';
Providers.globalProvider = new SimpleProvider((scopes: string[]) => {
// return a promise with accessToken
});
// set state to signal to all components to start calling graph
Providers.globalProvider.setState(ProviderState.SignedIn)