简体   繁体   English

React Router - 延迟认证后重定向

[英]React Router - Redirection after authentication with delay

I am trying to redirect once authentication in my react app is completed.我正在尝试在我的 React 应用程序中完成身份验证后重定向。 I use cognito (with aws amplify) to do the authentication (SSO).我使用 cognito(使用 aws amplify)进行身份验证 (SSO)。 Once authentication is completed, cognito will redirect the app to a page that we specify inside cognito ( /Dashboard ).身份验证完成后,cognito 会将应用程序重定向到我们在 cognito ( /Dashboard ) 中指定的页面。 And once the authentication is completed, our app page gets refreshed, as cognito redirects to a specific page.一旦身份验证完成,我们的应用程序页面就会刷新,因为 Cognito 会重定向到特定页面。

The problem here is, when cognito redirects to an endpoint url that we specify, after successful login, the token data is added to localstorage with a delay.这里的问题是,当 cognito 重定向到我们指定的端点 url 时,在成功登录后,令牌数据会延迟添加到 localstorage。 This cause my custom route component to check the local storage and says there is no token and user is not logged in.这导致我的自定义路由组件检查本地存储并说没有令牌并且用户未登录。

So as a workaround, im checking a condition in ' /Dashboard ' (Dashboard.js) if userDataInLocalstorage? <ShowAppHome>: <div>Loading...<div>因此,作为一种解决方法,如果userDataInLocalstorage? <ShowAppHome>: <div>Loading...<div> ,我会检查“ /Dashboard”(Dashboard.js ) 中的条件? userDataInLocalstorage? <ShowAppHome>: <div>Loading...<div>

Now if someone who is not logged in comes and hits the ' /Home ' - They will see only Loading... .现在,如果未登录的人过来并点击“ /Home ”——他们只会看到Loading... It wont redirect to /Login它不会重定向到/Login

Approach in my mind: Adding a timer of 5 second or something to check if cognito puts token.我心目中的方法:添加 5 秒或其他时间的计时器来检查 cognito 是否放置令牌。 After 5 sec, ill check again if token is there, if not ill redirect to /Login 5 秒后,再次检查令牌是否存在,如果不存在则重定向到 /Login

Its a bit messy stuff, but i would be greatful if someone can give some idea.它有点混乱,但如果有人能提供一些想法,我将不胜感激。

  1. User Logged In: Login > Cognito > cognito redirects to /Dashboard > Dashboard checks for user and its true用户登录:登录 > Cognito > cognito 重定向到 /Dashboard > Dashboard 检查用户及其真实情况

  2. User NOT logged in: Hits /Dashboard > Dashboard checks for user and its false > shows Loading...用户未登录:点击 /Dashboard > Dashboard 检查用户及其 false > 显示 Loading...

App.js应用程序.js

<Switch>
      <PublicRoute component={Login} path="/Login" exact />  //To redirect to /Dashboard/Home if  user is already logged in and hits /Login
      <Route path="/" exact>
          <Redirect to="/Login" />
      </Route>
      <Route component={Dashboard} path="/Dashboard" />
      <Route component={PageNotFound} />
</Switch>

PublicRoute.js公共路由.js

function PublicRoute({ component: Component, ...rest }) {
  const [userData, setUserData] = useState()
  const validateCurrentUser = async () => {
    try {
      const data = await Auth.currentAuthenticatedUser();
      setUserData(data.attributes)
      console.log("Public route currentAuthenticatedUser", userData);
    } catch (err) {
      console.log("Public route Please login to continue", userData);
    }
  };
  validateCurrentUser();

  return (
    <div>
      <Switch>
        <Route
          {...rest}
          render={(props) =>
            userData ? <Redirect to="/Dashboard/Home" /> : <Component {...props} /> 
          }
        />
      </Switch>
    </div>
  );
}

Dashboard.js仪表板.js

userDataInLocalstorage? (
        <SideNavComponentForAllPages/>
        <Switch>
            <Route path="/Dashboard" exact>
              <Redirect to="/Dashboard/Home" />
            </Route>
            <Route component={Home} path="/Dashboard/Home" exact />
            <Route component={Home2} path="/Dashboard/Home2" exact />
            
      </Switch>

) : <div>Loading...<div>

What about wrapping the function that checks localStorage inside a useEffect()?将检查 localStorage 的 function 包装在 useEffect() 中怎么样? This will ensure that the component has rendered before the check takes place.这将确保组件在检查发生之前已经呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 React 中使用 Firebase 成功登录后处理重定向 - Handling Redirection after successful login using Firebase in React Fonts 在使用反应路由器后无法反应 - Fonts doesn`t work in react after using react router 为什么在使用 React Router V6 保护路由时,我使用 AWS Amplify 的 React Authentication 组件会被无限渲染 - Why is my React Authentication component using AWS Amplify being rendered infinitely when using React Router V6 to protect routes 身份验证后立即检索自定义声明 Firebase/React - Retrieving custom claims Firebase/React immediately after authentication Flutter 创建实体后的 Riverpod 重定向 - Flutter Riverpod redirection after entity creation 重新加载私有路由页面后,用户将被重定向到登录页面。 [反应路由器] - after reloading the page of a private route, the user is redirected to the login page. [react router] AWS Amplify + React 身份验证问题(在 Auth.signIn() 登录后未获得 JWT 值) - AWS Amplify + React Authentication Issue (Not getting JWT value after Auth.signIn() on Sign) 使用 React 进行 Firebase 身份验证 - Firebase authentication with React Firebase 使用 React 进行谷歌身份验证 - Firebase Google Authentication with React AmplifyAuthenticator 与 react-router-dom - AmplifyAuthenticator with react-router-dom
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM