reactjs 使用Msal Provider React TS + Vite获取undefined(阅读'getLogger')

pkln4tw6  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(121)

我尝试使用ms-identity-javascript-react-tutorial来管理用户(登录/注册)。这是我遵循https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/3-Authorization-II/1-call-api/SPA的指南,但我认为由于我使用的是TypeScript,所以我没有正确初始化“intance”,因为它没有获得func getLogger。
我的AuthConfig是:

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */

import { LogLevel } from "@azure/msal-browser";

/**
 * Configuration object to be passed to MSAL instance on creation.
 * For a full list of MSAL.js configuration parameters, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
 */
export const msalConfig = {
    auth: {
        clientId: "Enter_the_Application_Id_Here", // This is the ONLY mandatory field that you need to supply.
        authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Defaults to "https://login.microsoftonline.com/common"
        redirectUri: "/", // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin
        postLogoutRedirectUri: "/", // Indicates the page to navigate after logout.
        clientCapabilities: ["CP1"] // this lets the resource owner know that this client is capable of handling claims challenge.
    },
    cache: {
        cacheLocation: "localStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
        secureCookies: false
    },
    system: {
        loggerOptions: {
            /**
             * Below you can configure MSAL.js logs. For more information, visit:
             * https://docs.microsoft.com/azure/active-directory/develop/msal-logging-js
             */
            loggerCallback: (level: any, message: any, containsPii: any) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            }
        }
    }
};

/**
 * Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
export const protectedResources = {
    apiTodoList: {
        endpoint: "http://localhost:5000/api/todolist",
        scopes: {
            read: [ "api://Enter_the_Web_Api_Application_Id_Here/Todolist.Read" ],
            write: [ "api://Enter_the_Web_Api_Application_Id_Here/Todolist.ReadWrite" ]
        }
    }
}

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
export const loginRequest = {
    scopes: [...protectedResources.apiTodoList.scopes.read, ...protectedResources.apiTodoList.scopes.write]
};

My Main.ts

import React from 'react'
import ReactDOM from 'react-dom/client'
import { EventType, PublicClientApplication } from '@azure/msal-browser';

import App from './App'
import './index.css'
import { msalConfig } from './utils/auth/AuthConfig';

const msalInstance = new PublicClientApplication(msalConfig);

// Default to using the first account if no account is active on page load
if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) {
  // Account selection logic is app dependent. Adjust as needed for different use cases.
  msalInstance.setActiveAccount(msalInstance.getAllAccounts()[0]);
}

msalInstance.addEventCallback((event: any) => {
  if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) {
      const account = event.payload.account;
      msalInstance.setActiveAccount(account);
  }
});

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <App msalInstance={msalInstance}/>
  </React.StrictMode>,
)

控制台输出:

caught TypeError: Cannot read properties of undefined (reading 'getLogger')
    at MsalProvider.tsx:107:25
    at mountMemo (react-dom.development.js:17225:19)
    at Object.useMemo (react-dom.development.js:17670:16)
    at useMemo (react.development.js:1650:21)
    at MsalProvider (MsalProvider.tsx:106:20)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
react-dom.development.js:18687 The above error occurred in the <MsalProvider> component:

    at MsalProvider (http://localhost:3011/node_modules/.vite/deps/@azure_msal-react.js?v=f9cbc1be:123:5)
    at App (http://localhost:3011/src/App.tsx?t=1681825109441:19:16)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:18687
react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'getLogger')
    at MsalProvider.tsx:107:25
    at mountMemo (react-dom.development.js:17225:19)
    at Object.useMemo (react-dom.development.js:17670:16)
    at useMemo (react.development.js:1650:21)
    at MsalProvider (MsalProvider.tsx:106:20)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)

项目依赖性:

"dependencies": {
    "@auth0/auth0-react": "^2.0.1",
    "@azure/msal-browser": "^2.35.0",
    "@azure/msal-react": "^1.5.3",
    "@emotion/styled": "^11.10.6",
    "@heroicons/react": "^2.0.17",
    "@react-google-maps/api": "^2.18.1",
    "@sentry/react": "^7.45.0",
    "@sentry/tracing": "^7.45.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@vitejs/plugin-react-swc": "^3.3.0",
    "axios": "^1.3.4",
    "clsx": "^1.2.1",
    "eslint-plugin-prettier": "^4.2.1",
    "jwt-decode": "^3.1.2",
    "msal": "^1.4.17",
    "react-datepicker": "^4.11.0",
    "react-input-mask": "^2.0.4",
    "uuid": "^9.0.0",
    "zxcvbn": "^4.4.2"
  },

我试过谷歌搜索,但没有找到同样的问题与MSAL提供商,我可以看到我做错了。

nukf8bse

nukf8bse1#

看起来你在项目中同时使用了@azure/msal-browsermsal (v1)。因为你使用的是@azure/msal-react,所以你应该只使用@azure/msal-browser (v2),并从依赖项中删除msal (v1)包。
请按照以下步骤解决此问题:
通过运行以下命令从依赖项中删除msal包:

npm uninstall msal

确保您安装了最新版本的@azure/msal-browser@azure/msal-react。您可以通过运行以下命令来更新它们:

npm install @azure/msal-browser@latest @azure/msal-react@latest

在您的Main.ts中,您将msalInstance作为prop传递给App组件。相反,您应该使用@azure/msal-react中的MsalProvider组件来 Package 您的App组件,并提供msalInstance作为上下文。如下所示更新您的Main.ts

import React from 'react';
import ReactDOM from 'react-dom';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';

import App from './App';
import './index.css';
import { msalConfig } from './utils/auth/AuthConfig';

const msalInstance = new PublicClientApplication(msalConfig);

// ... (rest of your code)

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>,
);

App.tsx中,您不再需要将msalInstance作为prop传递。您可以将其从App组件的prop中删除。
完成这些更改后,您的应用程序应该可以正确地使用MSAL v2库和@azure/msal-react包。

相关问题