Error acquiring token while using react app for azure.

huangapple go评论267阅读模式
英文:

Error acquiring token while using react app for azure

问题

这是我的 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/", // 设置正确的重定向 URL
  },
};

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

    initializeMsal();
  }, []);

  const getAccessToken = async () => {
    if (!initialized) {
      console.log("MSAL 尚未初始化");
      return;
    }

    try {
      const response = await pca.acquireTokenPopup({
        scopes: ["https://graph.microsoft.com/User.Read"], // 替换为所需的范围
        interactionType: InteractionType.Popup,
      });

      if (response.accessToken) {
        setAccessToken(response.accessToken);
      }
    } catch (error) {
      console.error("获取令牌时出错:", error);
    }
  };

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

  return (
    <div className="App">
      <h1>访问令牌{accessToken}</h1>
    </div>
  );
}

export default App;

我正在尝试从 Azure 获取访问令牌,但当我运行它时,出现错误:

Error acquiring token: BrowserAuthError: uninitialized_public_client_application: 在尝试调用任何其他 MSAL API 之前,您必须调用并等待 initialize 函数。

我尝试运行 npm start 后,我收到以下错误:

Error acquiring token: BrowserAuthError: uninitialized_public_client_application: 在尝试调用任何其他 MSAL API 之前,您必须调用并等待 initialize 函数。

英文:

this is my app.js

    import React, { useEffect, useState } from &quot;react&quot;;
import { PublicClientApplication, InteractionType } from &quot;@azure/msal-browser&quot;;
const msalConfig = {
auth: {
clientId: &quot;f87c7548-4942-46cf-a69b-c0dccc5f5b1f&quot;,
authority:
&quot;https://login.microsoftonline.com/63cdbcad-50c7-45d4-961c-b36bcfdab344&quot;,
redirectUri: &quot;http://localhost:3000/&quot;, // Set the correct redirect URL
},
};
function App() {
const [accessToken, setAccessToken] = useState(&quot;&quot;);
const [initialized, setInitialized] = useState(false);
const pca = new PublicClientApplication(msalConfig);
useEffect(() =&gt; {
const initializeMsal = async () =&gt; {
await pca.initialize(); // Initialize MSAL instance
setInitialized(true);
};
initializeMsal();
}, []);
const getAccessToken = async () =&gt; {
if (!initialized) {
console.log(&quot;MSAL not initialized yet&quot;);
return;
}
try {
const response = await pca.acquireTokenPopup({
scopes: [&quot;https://graph.microsoft.com/User.Read&quot;], // Replace with necessary scopes
interactionType: InteractionType.Popup,
});
if (response.accessToken) {
setAccessToken(response.accessToken);
}
} catch (error) {
console.error(&quot;Error acquiring token:&quot;, error);
}
};
useEffect(() =&gt; {
if (initialized) {
getAccessToken();
}
}, [initialized]);
return (
&lt;div className=&quot;App&quot;&gt;
&lt;h1&gt;Access Token: {accessToken}&lt;/h1&gt;
&lt;/div&gt;
);
}
export default App;`

i am trying to get access token from azure but when i am running this it is giving error

Error acquiring token: BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.

i tried npm start after that i get this error

Error acquiring token: BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.

答案1

得分: 1

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

此外,在实例化后立即调用getAccessToken,而不检查MSAL是否正确初始化。考虑到MSAL中缺少初始化方法,第一个useEffect是不必要的。

英文:

In the MSAL library for browser-based applications, there's no initialize method for PublicClientApplication. Hence, your call to await pca.initialize(); is likely causing an error. You don't need to manually initialize PublicClientApplication as it gets initialized when you instantiate it with the configuration.

Also you are essentially calling getAccessToken immediately after instantiation, without checking if MSAL is properly initialized. Given the absence of the initialize method in MSAL, the first useEffect isn't necessary.

huangapple
  • 本文由 发表于 2023年8月11日 00:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定