我正在 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 页面,以及导致此行为的潜在原因是什么。任何帮助或见解将不胜感激。谢谢!
当您使用
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);
}
};
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 />} />
结果