【问题标题】:Protect Routes/Pages with NextJs使用 NextJs 保护路由/页面
【发布时间】:2021-11-23 09:48:40
【问题描述】:

我建立了一个简单的项目,通过使用 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;

withAuth 使用示例

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

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

export default withAuth(sample);

【问题讨论】:

    标签: javascript reactjs security next.js


    【解决方案1】:

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

    getServerSideProps中检查用户是否登录

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

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

    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 }
        }
    }
    

    【讨论】:

    • 是否有可能使用getStaticProps 和redux state 完成相同的任务?
    • @PrajwalKulkarni 这适用于服务器端生成的页面,对于静态生成的页面,我建议您查看this postthis one as well
    • 感谢链接资源,通过这两个链接。但是,他们在那里使用自定义钩子以及 API 路由中的中间件身份验证。我一直在寻找带有 redux 解决方法的 SSG。有可能吗?另外,当我通过身份验证并尝试通过在地址栏中手动输入 URL 来访问受保护的路由时,redux 状态丢失并且我被重定向到身份验证页面,是什么导致了这种行为?
    • 我只是有一个问题你怎么做我使用graphql而不是restapi我试图得到类似const data = localStorage.getItem("jwtToken")然后我使用if语句但它不起作用它总是返回false
    • @MohammadKhan 如果您将token 存储在local storage 中(在用户首次登录应用程序之后),请在请求获取一些用户信息时使用该令牌,如果您有权限用户的令牌,您应该获得一些信息。如果你没有得到任何信息,那么那不是正确的用户并将他们重定向到登录页面。
    猜你喜欢
    • 2020-04-26
    • 2016-04-15
    • 1970-01-01
    • 2020-11-21
    • 2020-09-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多