首页 > 解决方案 > 在 React 应用程序中实现 Microsoft 登录时出现 CORS 策略错误

问题描述

在此处输入图像描述

我正在尝试实现 SPA Microsoft 登录,我想要登录弹出窗口中的代码,这就是为什么我在 authConfig.js 中添加了授权 URL,例如“https://login.microsoftonline.com/common/oauth2/v2.0/authorize /?client_id=xyz&response_type=code&redirect_uri=http://localhost:3002&response_mode=query&scope=offline_access https://graph.microsoft.com/Contacts.Read https://graph.microsoft.com/User.Read&state=12345"但是这个URL 抛出 CROS 和 ClientAuthError: endpoints_resolution_error 错误

authConfig.js

/*
 * 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: "xyz",
    authority:
      "https://login.microsoftonline.com/common/oauth2/v2.0/authorize/?client_id=xyz&response_type=code&redirect_uri=http://localhost:3002&response_mode=query&scope=offline_access https://graph.microsoft.com/Contacts.Read https://graph.microsoft.com/User.Read&state=12345",
    redirectUri: "http://localhost:3002",
  },
  cache: {
    cacheLocation: "sessionStorage", // This configures where your cache will be stored
    storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        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;
        }
      },
    },
  },
};

/**
 * 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: ["User.Read", "Contacts.Read"],
};

/**
 * Add here the scopes to request when obtaining an access token for MS Graph API. 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 graphConfig = {
  graphMeEndpoint: "Enter_the_Graph_Endpoint_Herev1.0/me",
};

登录按钮.jsx

import React from "react";
import { useMsal } from "@azure/msal-react";
import { loginRequest } from "../authConfig";
import DropdownButton from "react-bootstrap/DropdownButton";
import Dropdown from "react-bootstrap/esm/Dropdown";

/**
 * Renders a drop down button with child buttons for logging in with a popup or redirect
 */
export const SignInButton = () => {
  const { instance } = useMsal();

  const handleLogin = (loginType) => {
    if (loginType === "popup") {
      instance
        .loginPopup(loginRequest)
        .then(async (data) => {
          // Here I want response in Code format so I can use this code to get refresh token 
        })
        .catch((e) => {
          console.log(e);
        });
    } else if (loginType === "redirect") {
      instance.loginRedirect(loginRequest).catch((e) => {
        console.log(e);
      });
    }
  };
  return (
    <DropdownButton
      variant="secondary"
      className="ml-auto"
      drop="left"
      title="Sign In"
    >
      <Dropdown.Item as="button" onClick={() => handleLogin("popup")}>
        Sign in using Popup
      </Dropdown.Item>
      <Dropdown.Item as="button" onClick={() => handleLogin("redirect")}>
        Sign in using Redirect
      </Dropdown.Item>
    </DropdownButton>
  );
};

任何人都可以向我建议如何从登录弹出窗口获取响应类型作为代码,或者如何从同意屏幕获取刷新令牌?

我参考这个文档https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-react

标签: reactjsoauthmsal

解决方案


推荐阅读