使用msal-browser与Microsoft Graph Toolkit

4
我正在开发一个React应用程序,使用@azure/msal-react库进行身份验证。 这很好用,但后来我意识到我想使用@microsoft/mgt-react库中的人员选择器小部件。 是否有任何方法可以将现有的@azure/msal-react / @azure/msal-browser库与MGT库连接起来? 或者我必须重构代码以使用MGT样式的身份验证方法? 如果是这种情况,我想我会自己构建People Picker组件,但我想看看是否可能。

嗯,我又读了一些资料,看起来我需要设置一个“自定义提供程序”,我走对了吗? https://learn.microsoft.com/en-us/graph/toolkit/providers/custom - John McAulay
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4

我的解决方案是在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])

  ... 

}

3
如果您已经有获取访问令牌的方法,您可以使用SimpleProvider与MGT一起使用。请注意保留HTML标签。
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)

非常感谢,我在之前的文档中找到了答案(请参见上面的评论)。我正在努力解决i的问题,但我相信今晚我可以弄清楚它。如果我有更多问题,我会在这里发布,但这绝对是答案。非常感谢。 - John McAulay
谢谢兄弟,我把它解决了!非常感谢你迅速的回复。 - John McAulay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,