instance.loginRedirect() 不重定向的问题

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

我正在 React 应用程序中设置 Azure 单点登录 (Azure AD SSO),并且在使用 instance.loginRedirect() 时遇到问题。

问题来了:

当我使用 instance.loginPopup() 时,身份验证过程工作正常。成功登录后,它会按预期将我重定向到 /profile 页面。

但是,当我使用 instance.loginRedirect() 时,行为并不符合预期。成功登录后,我将被重定向到“登录”页面,而不是“/个人资料”页面。

应用程序.tsx

import React from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'; // Import Navigate from react-router-dom
import { MsalProvider, AuthenticatedTemplate, useMsal } from '@azure/msal-react';
import { PublicClientApplication } from '@azure/msal-browser';
import SignInRoute from './components/SignInRoute';
import ProfileRoute from './components/Profile';

const msalConfig = {
  auth: {
    clientId: 'client_id',
    authority: 'https://login.microsoftonline.com/tenant_id',
    redirectUri: 'http://localhost:3000',
  },
  cache: {
    cacheLocation: 'localStorage',
  },
};

const msalInstance = new PublicClientApplication(msalConfig);

const App: React.FC = () => {
  const { accounts } = useMsal();
  const isAuthenticated = accounts.length > 0;

  return (
    <MsalProvider instance={msalInstance}>
      <Router>
        <div className="App">
          <Routes>
            <Route path="/SignIn" element={<SignInRoute />} />
            {/* Add a Route to redirect from / to /SignIn */}
            <Route path="/" element={<Navigate to="/SignIn" />} />
            <Route path="/profile" element={<ProfileRoute />} />

          </Routes>
          <AuthenticatedTemplate>
            {isAuthenticated && (
              <button onClick={() => msalInstance.logout()}>Sign Out</button>
            )}
          </AuthenticatedTemplate>
        </div>
      </Router>
    </MsalProvider>
  );
};

export default App;

登录.tsx

import React from 'react';
import { useMsal } from '@azure/msal-react';
import '../css/SignIn.css';

import logo from '../images/logo.png';

const SignIn: React.FC = () => {
  const { instance } = useMsal();
  const { accounts } = useMsal();

  const handleSignIn = async () => {
    try {
      await instance.loginPopup();
      // Redirect to the profile page upon successful sign-in
      window.location.href = '/profile';
    } catch (error) {
      console.error('Error signing in:', error);
    }
  };

  // If the user is already authenticated, redirect to the profile page
  if (accounts.length > 0) {
    window.location.href = '/profile';
  }

  return (
    <div className="signin-container">
      <div className="logo-and-text">
        <img src={logo} alt="logo" className="logo" />
        <h2 className="signin-text">Sign In</h2>
      </div>
      <button className="signin-button" onClick={handleSignIn}>
        Sign In with Azure AD
      </button>
    </div>
  );
};

export default SignIn;

SingInRoute.tsx

import React, { Suspense, lazy } from 'react';

const SignIn = lazy(() => import('./SignIn'));

const SignInRoute: React.FC = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <SignIn />
    </Suspense>
  );
};

export default SignInRoute;

我想了解为什么 instance.loginRedirect() 在成功登录后没有将我重定向到 /profile 页面,以及导致此行为的潜在原因是什么。任何帮助或见解将不胜感激。谢谢!

typescript azure-active-directory single-sign-on azure-ad-msal react-typescript
1个回答
0
投票

当您使用

instance.loginPopup()
时,这是一个异步操作,您可以控制登录成功后发生的情况(即使用
/profile
手动重定向到
window.location.href = '/profile'
页面)。

另一方面,

instance.loginRedirect()
适用于基于重定向的身份验证,其中页面被重定向到身份提供商进行身份验证,然后返回到您的应用程序。在这种情况下,到
/profile
页面的重定向应由库在成功验证后处理。

  • 确保在身份验证过程完成之前不会重定向到
    /profile
    。在您的
    handleSignIn
    函数中,尝试删除手动重定向并让库处理它。
const handleSignIn = async () => {
  try {
    await instance.loginPopup();
    // No manual redirect here
  } catch (error) {
    console.error('Error signing in:', error);
  }
};
  • 处理重定向流程中的错误。您可以使用 MSAL 中的
    handleRedirectCallback
    方法来处理重定向回调并检查错误。
useEffect(() => { instance.handleRedirectCallback().then(() => {
 // Check for errors and redirect to the appropriate page  
 if (instance.getAccount()) {
  window.location.href = '/profile'; } }); 
  }, 
[instance]);
  • 确保
    /profile
    路由已正确配置且可访问

<Route path="/profile" element={<ProfileRoute />} />

结果 enter image description here

enter image description here enter image description here

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