Reputation: 305
I am working on a React App and am using the @azure/msal-react library for authentication.
This is working great , but then I realized I'd quite like to use the people picker widget from the @microsoft/mgt-react library.
Is there any way I can wire up my existing @azure/msal-react / @azure/msal-browser libraries to the MGT library?
Or do I have to refactor my code to use the MGT style auth methods?
If that's the case I'll just build my own People Picker component I think, but I thought I'd see if it was possible anyway.
Upvotes: 5
Views: 1668
Reputation: 10167
My solution is to use the same @azure/msal-browser
instance in both the Microsoft Graph Toolkit (@microsoft/mgt-element
) and @azure/msal-react
libraries, like so:
// 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')
);
And then do a little bootstrapping in the app component to keep the login states in sync:
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])
...
}
Upvotes: 4
Reputation: 566
If you already have a way to get an access token, you can use MGT with the SimpleProvider.
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)
Upvotes: 3