首页 > 解决方案 > Nextjs auth 使用外部端点的保护路由设置

问题描述

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

我的情况非常简单。我需要对用户资料和订单历史记录等少数页面实施 OTP 登录。其他页面将保持不受保护,如主页、产品列表、产品详细信息等。

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

我对下一个身份验证非常困惑,并且那里有太多的身份验证方法。

我尝试了以下。

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

//页面/profile.js

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

const accessToken = Cookies.get('token');问题是始终无法从 Cookie 中获取令牌undefined。但是Cookies设置成功。

请向我建议简单的方法以及所有 nextjs 功能在哪里可以使用。

标签: reactjsnext.jsnext-auth

解决方案


推荐阅读