Microsoft SSO 登录在 React 应用程序中未按预期工作

问题描述 投票:0回答:1

我正在尝试使用客户端 ID、租户 ID 的 SSO 登录动态凭据在我的 React 应用程序中进行 Microsoft SSO 登录。问题是它不起作用。它只会打开一个弹出页面,当我单击用户帐户时,它只会简单地重定向到同一页面中的重定向网址,而不是关闭并向我返回结果。

当我从数据库获取相同的凭据,但当我使用它们硬编码时,它会按照需要完美工作。

我已经检查了从数据库获取的数据,它在那里工作正常,因此尝试解决它,但我不知道为什么它会这样。

下面是我的代码

function LoginButton() {
  const { instance } = useMsal();

  const handleLogin = async() => {
    instance.loginPopup().then((response) => {
      console.log(response);
    }).catch((error) => {
      console.log(error);
    });
  }

  return <button type="button" onClick={handleLogin} className="btn btn-primary">Login</button>;
}

function App() {
  const [msalConfig, setMsalConfig] = useState<Configuration | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  
  useEffect(() => {
    const MFTLogin = async () => {
      const subdomain = window.location.hostname.split('.')[0];
      const storedConfig = localStorage.getItem('msalConfig');

      if (storedConfig) {
        setMsalConfig(JSON.parse(storedConfig));
        setIsLoading(false);
      } else if (subdomain) {
        // Fetch and set MSAL configuration
        const request = await axios.get(`http://localhost:5000/outlook/organization/${subdomain}`);
        if (request && request.data) {
          const data: Configuration = {
            auth: {
              clientId: request.data.data.outlook_client_id_mfo,
              authority: `https://login.microsoftonline.com/${request.data.data.outlook_tenant_id_mfo}`,
              redirectUri: "http://localhost:3000",
            }
          };
          localStorage.setItem('msalConfig', JSON.stringify(data));
          setMsalConfig(data);
        }
        setIsLoading(false);
      }
    };

    MFTLogin();
  }, []);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (!msalConfig) {
    return <div>Configuration Error</div>;
  }

  const msalInstance = new PublicClientApplication(msalConfig);

  return (
    <MsalProvider instance={msalInstance}>
      <div className="App">
        <LoginButton />
      </div>
    </MsalProvider>
  );
}

export default App;
javascript reactjs azure-active-directory microsoft-graph-api onelogin
1个回答
0
投票

我尝试了以下代码,并且能够使用客户端 ID、租户 ID 的 SSO 登录的动态凭据登录到我的 React 应用程序。

代码:

src/components/LoginButton.js :

import React from 'react';
import { useMsal } from '@azure/msal-react';
import { setMsalConfig } from '../services/authService'; 
import { fetchMsalConfigFromApi } from '../services/apiService'; 

const LoginButton = () => {
  const { instance } = useMsal();

  const handleLogin = async () => {
    let apiConfig; 

    try {
      const subdomain = window.location.hostname.split('.')[0];
      apiConfig = await fetchMsalConfigFromApi(subdomain);

      setMsalConfig({
        auth: {
          clientId: apiConfig.outlook_client_id_mfo,
          authority: `https://login.microsoftonline.com/${apiConfig.outlook_tenant_id_mfo}`,
          redirectUri: 'http://localhost:3000',
        },
      });

      await instance.loginPopup();
    } catch (error) {
      console.log('Error during login:', error);
    }
  };

  return (
    <button type="button" onClick={handleLogin} className="btn btn-primary">
      Login
    </button>
  );
};

export default LoginButton;

src/services/apiService.js :

import axios from 'axios';
const fetchMsalConfigFromApi = async (subdomain) => {
  try {
    const response = await axios.get(`http://localhost:5000/outlook/organization/`);
    return response.data.data;
  } catch (error) {
    console.error('Error fetching MSAL config from API:', error);
    throw error;
  }
};

export { fetchMsalConfigFromApi };

服务器/server.js:

const express = require('express');
const cors = require('cors');
const app = express();
const port = 5000;

const msalConfig = {
  outlook_client_id_mfo: '<client_ID>',
  outlook_tenant_id_mfo: '<tenant_ID>',
};

app.use(cors());

app.get('/outlook/organization', (req, res) => {
  res.json({
    success: true,
    data: msalConfig,
  });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

我在应用程序身份验证中添加了以下URL作为单页应用程序,如下所示,

 http://localhost:3000

enter image description here

输出:

服务器端代码运行在端口 5000 上,如下所示,

enter image description here

我在浏览器中得到了以下输出和上面的输出URL

enter image description here

客户端代码在端口 3000 上运行,如下所示,

enter image description here

我单击“登录”按钮并选择我的帐户进行登录。我已经可以登录了。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.