【问题标题】:Use Microsoft Graph Toolkit with msal-browser将 Microsoft Graph Toolkit 与 msal-browser 一起使用
【发布时间】:2021-09-02 20:24:36
【问题描述】:

我正在开发一个 React 应用程序,并且正在使用 @azure/msal-react 库进行身份验证。

这很好用,但后来我意识到我很想使用 @microsoft/mgt-react 库中的人员选择器小部件。

有什么方法可以将我现有的 @azure/msal-react / @azure/msal-browser 库连接到 MGT 库?

或者我是否必须重构我的代码才能使用 MGT 风格的身份验证方法?

如果是这样的话,我想我会构建自己的 People Picker 组件,但我想我会看看是否有可能。

【问题讨论】:

标签: reactjs msal microsoft-graph-toolkit


【解决方案1】:

如果您已经有办法获取访问令牌,则可以将 MGT 与 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)

【讨论】:

  • 非常感谢,我在之前的文档中发现了这一点(见上面的评论)。我正在为我挣扎,但我相信今晚我能解决这个问题。如果我还有其他问题,我会在这里发布,但这绝对是答案。非常感谢。
  • 干杯兄弟,我整理好了!非常感谢您的快速回复。
【解决方案2】:

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

  ... 

}

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多