【问题标题】:How to add Nextjs cookie based secure authentication?如何添加基于 Nextjs cookie 的安全身份验证?
【发布时间】:2021-09-20 08:29:55
【问题描述】:

我有一个小问题。我对 Nextjs 非常非常陌生,我正在尝试通过制作应用程序来学习。我已经设法使用 next 创建了一个登录系统,并且在保护路由时几乎没有问题。成功登录后我已经成功添加了一个cookie。现在我想在用户转到受保护的路线时验证 cookie。我使用this 教程按照以下步骤操作。

  1. 制作了一个高阶组件并使用它检查了 cookie 验证。
  2. 使用它来包装受保护的组件。

下面是我的 HOD。

import { useRouter } from "next/router";
import Cookies from 'js-cookie';

const withAuth = (WrappedComponent) => {
  return (props) => {
    if (typeof window !== "undefined") {
      const Router = useRouter();

      const accessToken = Cookies.get('token');
      if (!accessToken) {
        Router.replace("/");
        return null;
      }
      return <WrappedComponent {...props} />;
    }
    return null;
  };
};

export default withAuth;

然后我使用上面的 HOD 包装了我的组件。

import React, { Component } from 'react';
import withAuth from '../utils/withAuth';
class Home extends Component {
  render() {
    return (
      <div>
        HOME
      </div>
    );
  }
}

export default withAuth(Home);

问题 #1 HOD 上方显示控制台警告,内容如下。

警告:预期的服务器 HTML 将包含 . div

反正我可以解决这个问题吗?根据一些 github 答案,我发现这可以使用 useEffect 解决。 SOURCE 谁能帮我解决这个问题?

问题 #2 这样,我必须用我的 HOD 包装每个受保护的组件。这是执行此操作的正确方法还是有任何其他方法可以做得更好?

非常感谢您或您的支持。

【问题讨论】:

    标签: javascript reactjs authentication cookies next.js


    【解决方案1】:

    过了一段时间。我能够通过使用下面的代码来解决这个问题。现在我只想知道上面提到的第二期的答案。

    ISSUE #2 这样,我必须用我的 HOD 包装每个受保护的组件。这是执行此操作的正确方法还是有任何其他方法可以做得更好?

    非常感谢您或您的支持。

    我用来解决问题的代码

    import Router from 'next/router'
    import Cookies from 'js-cookie';
    import React, { useState, useEffect } from 'react';
    
    const withAuth = (WrappedComponent) => {
      return (props) => {
        const [isLoggedIn, setLoginStatus] = useState(false);
        useEffect(() => {
          if (typeof window !== "undefined") {
            const accessToken = Cookies.get('token');
            if (accessToken) {
              setLoginStatus(true)
            }
            else {
              Router.push("/")
            }
          }
        }, []);
        if (isLoggedIn) {
          return <WrappedComponent {...props} />;
        } else {
          return null;
        }
      }
    };
    
    export default withAuth;
    

    【讨论】:

    • 嗨,你能解决这个问题吗?
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2021-08-13
    • 2023-03-31
    • 2013-07-20
    • 1970-01-01
    • 2013-01-20
    • 2020-01-23
    • 2010-11-19
    相关资源
    最近更新 更多