reactjs - 使用 Azure 的 React 应用程序时获取 token 时出错

标签 reactjs azure azure-active-directory

这是我的 app.js

    import React, { useEffect, useState } from "react";
    import { PublicClientApplication, InteractionType } from "@azure/msal-browser";

    const msalConfig = {
    auth: {
    clientId: "f87c7548-4942-46cf-a69b-c0dccc5f5b1f",
    authority:
      "https://login.microsoftonline.com/63cdbcad-50c7-45d4-961c-b36bcfdab344",
    redirectUri: "http://localhost:3000/", // Set the correct redirect URL
   },
   };

    function App() {
   const [accessToken, setAccessToken] = useState("");
   const [initialized, setInitialized] = useState(false);
   const pca = new PublicClientApplication(msalConfig);
   useEffect(() => {
    const initializeMsal = async () => {
      await pca.initialize(); // Initialize MSAL instance
      setInitialized(true);
    };

    initializeMsal();
   }, []);

   const getAccessToken = async () => {
    if (!initialized) {
      console.log("MSAL not initialized yet");
      return;
    }

    try {
      const response = await pca.acquireTokenPopup({
        scopes: ["https://graph.microsoft.com/User.Read"], // Replace with necessary scopes
        interactionType: InteractionType.Popup,
      });

      if (response.accessToken) {
        setAccessToken(response.accessToken);
      }
    } catch (error) {
      console.error("Error acquiring token:", error);
    }
    };

   useEffect(() => {
    if (initialized) {
      getAccessToken();
    }
    }, [initialized]);

    return (
    <div className="App">
      <h1>Access Token: {accessToken}</h1>
    </div>
    );
    }

    export default App;`

我正在尝试从azure获取访问 token ,但是当我运行它时,它给出了错误

获取 token 时出错:BrowserAuthError:uninitialized_public_client_application:在尝试调用任何其他 MSAL API 之前,必须调用并等待初始化函数。

我尝试了 npm start 之后出现此错误

获取 token 时出错:BrowserAuthError:uninitialized_public_client_application:在尝试调用任何其他 MSAL API 之前,必须调用并等待初始化函数。

最佳答案

在基于浏览器的应用程序的 MSAL 库中,没有 PublicClientApplication 的初始化方法。因此,您可以调用await pca.initialize();可能会导致错误。您不需要手动初始化 PublicClientApplication,因为当您使用配置实例化它时它就会被初始化。

此外,您实际上是在实例化后立即调用 getAccessToken,而不检查 MSAL 是否已正确初始化。由于 MSAL 中缺少初始化方法,因此不需要第一个 useEffect。

关于reactjs - 使用 Azure 的 React 应用程序时获取 token 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76877599/

相关文章:

c# - 如何为我的 React/.NET Core 3.0 SPA Web 应用程序添加 Microsoft Identity/Azure AD 登录功能

reactjs - axios.delete(url[,config]) : Type has no properties in common with type 'AxiosRequestConfig'

reactjs - 如何将 Google 的gapi 与Reactjs 结合使用?

azure-web-app-service - Azure 移动应用程序仅使用 Azure AD 进行身份验证,但 Windows 帐户也可以登录?

azure - 无法连接到 Azure 文件共享

azure - 如何延长Azure自定义脚本扩展默认超时?

azure - Office 365:刷新访问 token 结果并出现 "AADSTS9002313"invalid_grant 异常

html - 我将如何在 css 中创建图像拱门

reactjs - 如何将父状态传递给其子组件?

c# - Microsoft.Azure.WebHosts.JobHostConfiguration 的替代品是什么