Reactjs 使用外部端点设置Nextjs auth保护的路由

Reactjs 使用外部端点设置Nextjs auth保护的路由,reactjs,next.js,next-auth,Reactjs,Next.js,Next Auth,我是NextJs的新手。我熟悉ReactJs和ProtectedRoute(我的自定义组件),它们使用本地存储令牌 我的设想非常直截了当。我需要实现OTP登录的几个页面,如用户配置文件和订单历史等,其他页面将保持不受保护,如主页,产品列表,产品详细信息等 我需要返回令牌的外部服务器登录端点。我需要在成功令牌接收时允许受保护路由,并在手动注销之前使用它 关于下一个auth,我非常困惑,并且有太多的auth方法 我尝试了以下方法 钩子 问题是无法从Cookiesconst accessToken=C

我是NextJs的新手。我熟悉ReactJs和ProtectedRoute(我的自定义组件),它们使用本地存储令牌

我的设想非常直截了当。我需要实现OTP登录的几个页面,如用户配置文件和订单历史等,其他页面将保持不受保护,如主页,产品列表,产品详细信息等

我需要返回令牌的外部服务器登录端点。我需要在成功令牌接收时允许受保护路由,并在手动注销之前使用它

关于下一个auth,我非常困惑,并且有太多的auth方法

我尝试了以下方法

钩子

问题是无法从Cookies
const accessToken=Cookies.get('token')中获取令牌总是
未定义
。但是
Cookies
设置成功


请向我推荐一种简单的方法,以及所有nextjs功能在哪里工作。

服务器端,cookie包含在HTTP请求中。所以你不能只做“Cookies”,你需要使用一个通用库,在那里你可以做“Cookies(req)”之类的事情。顺便说一下,我强烈建议不要在下一篇文章中直接使用服务器端重定向,这是一种反模式。有关更多详细信息,请参见以下问题:正如Blitz.js doc所说:安全的数据,而不是页面。
import React from 'react';
import Router from 'next/router';
import Cookies from 'js-cookie';

const login = '/'; // Define your login route address.

/**
 * Check user authentication and authorization
 * It depends on you and your auth service provider.
 * @returns {{auth: null}}
 */
const checkUserAuthentication = () => {
    const accessToken = Cookies.get('token');

    if (accessToken === undefined) {
        return { auth: null }; // change null to { isAdmin: true } for test it.
    } else {
        return { auth: true };
    }
};

const WrappedComponent = () => {

    const hocComponent = ({ ...props }) => <WrappedComponent {...props} />;

    hocComponent.getInitialProps = async (context) => {
        const userAuth = checkUserAuthentication();

        // Are you an authorized user or not?
        if (!userAuth?.auth) {
            // Handle server-side and client-side rendering.
            if (context.res) {
                context.res?.writeHead(302, {
                    Location: login,
                });
                context.res?.end();
            } else {
                Router.replace(login);
            }
        } else if (WrappedComponent.getInitialProps) {
            const wrappedProps = await WrappedComponent.getInitialProps({ ...context, auth: userAuth });
            return { ...wrappedProps, userAuth };
        }

        return { userAuth };
    };

    return hocComponent;
};

export default WrappedComponent
import withAuth from "./withAuth";
export default withAuth(Profile);