我试图重定向到主页后,登录身份验证使用Azure Msal库。但是在身份验证之后,它重定向回登录数秒钟,然后转到主页。我已经粘贴了下面的代码。请帮帮忙。
login.tsx
import { SignInButton } from "../../components/button";
const Login:React.FC = () => {
return(
<div>
<SignInButton />
</div>);
}私人Route.tsx
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { useIsAuthenticated, useMsal } from "@azure/msal-react";
import '../../theme/styles.css';
const PrivateRoute: React.FC<{
component?: React.FC;
path: string;
exact: boolean;
render?: any;
isLoggedIn: boolean
}> = (props) => {
const { component, path, exact } = props;
const isAuthenticated = useIsAuthenticated();
const {instance, accounts, inProgress} = useMsal();
return (isAuthenticated) ? (<Route path={path} exact={exact} component={component}/>) : (<Redirect to="/login" />);
};
export default PrivateRoute;App.tsx
//other imports
import Login from './pages/login';
import PrivateRoute from './components/privateroute';
import { useHistory } from "react-router";
import { useIsAuthenticated, useMsal } from '@azure/msal-react';
const App: React.FC = () => {
const isAuth = useIsAuthenticated();
const history = useHistory();
useEffect(() => {
if(isAuth){
history.push("/");
}
},[isAuth])
return (
<IonApp>
<Layout>
<Switch>
<PrivateRoute exact path="/" isLoggedIn={true} component={Home} />
<PrivateRoute exact path="/frsevents" isLoggedIn={true} component={FRSEvents} />
</Switch>
</Layout>
<Route exact path="/login" component={Login} />
</IonApp>
);
}
export default App; 发布于 2022-03-31 12:54:57
·MSAL支持传递‘redirectStartPage’参数,该参数告诉MSAL从重定向返回后导航到哪里。注意,这需要启用‘auth.navigateToLoginRequestUrl’。使用此参数的步骤如下:
const redirectStartPage = this.getDestinationUrl(url);
this.authService.loginRedirect({
redirectStartPage,
scopes: this.msalAngularConfig.consentScopes,
extraQueryParameters: this.msalAngularConfig.extraQueryParameters要更多地了解上述参数的正确使用,请参阅示例角(Reactjs)应用程序代码,因为它说明如何在下面的链接中使用MSAL角:-
·此外,供您参考,请阅读下面的Github问题,其中讨论MSAL React应用程序的重定向流程如下:
a.受保护的路由检查.getAccount()是否返回数据。如果没有-用户重定向到/login。
登录页面注册一个回调registerRedirectionCallback,如果.getAccount()没有返回- auth.loginRedirect(GRAPH_REQUESTS.LOGIN)被执行。
一旦帐户在那里,它就会将用户重定向到先前的路径。
如果API接收到错误代码401,我将执行window.location.reload()
https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/1474
https://stackoverflow.com/questions/71671755
复制相似问题