使用 NextJs 保护路由/页面

Moh*_*han 0 javascript security reactjs next.js

我构建了一个简单的项目,通过使用 if 和 else 语句并将每个页面放入一个函数来保护网站的路由/页面withAuth(),但我不确定这是否是使用 nextjs 保护路由的最佳方法,我注意到保护路由或页面存在延迟,例如 2-3 秒长,在将访问者或未注册用户重定向到登录页面之前,他们可以看到页面的内容。

有没有办法摆脱它或使请求更快,以便未注册的用户无法查看页面的内容?nextjs框架中是否有更好的方法来保护某个路由?

代码


import { useContext, useEffect } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";

const withAuth = (Component) => {
  const Auth = (props) => {
    const { user } = useContext(AuthContext);

    useEffect(() => {
      if (!user) Router.push("/login");
    });

    return <Component {...props} />;
  };

  return Auth;
};

export default withAuth;
Run Code Online (Sandbox Code Playgroud)

withAuth 使用示例

import React from "react";
import withAuth from "./withAuth";

function sample() {
  return <div>This is a protected page</div>;
}

export default withAuth(sample);
Run Code Online (Sandbox Code Playgroud)

wav*_*per 5

您可以在服务器端对用户进行身份验证,如果用户登录,则向他们显示受保护路由的内容,否则将他们重定向到其他路由。请参阅此页面了解微尘信息。

检查getServerSideProps用户是否已经登录

   if (!data.username) {
        return {
            redirect: {
                destination: '/accounts/login',
                permanent: false,
            },
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是受保护的路由页面的完整示例

export default function SomeComponent() {
    // some content
}

export async function getServerSideProps({ req }) {

    const { token } = cookie.parse(req.headers.cookie)

    const userRes = await fetch(`${URL}/api/user`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })

    const data = await userRes.json()

    // does not allow access to page if not logged in 
    if (!data.username) {
        return {
            redirect: {
                destination: '/accounts/login',
                permanent: false,
            },
        }
    }

    return {
        props: { data }
    }
}
Run Code Online (Sandbox Code Playgroud)