reactjs - 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 功能在哪里可以使用。
解决方案
推荐阅读
- c# - .NET Core 3.1 Sdk.Worker 与 Sdk.Web Razor 模板?(Sdk.Web 做了什么来允许 Razor 模板?)
- python - Selenium 帮助切换到 iframe 然后点击链接
- mysql - sql编码中的日期间隔
- reactjs - TypeScript 和 JSX 不理解我想设置特定道具时的情况
- firebase - 将 vuexfire 与模块一起使用时如何处理突变?
- networking - 如果我正在体验完美的互联网连接,为什么“ping google.com”会返回 100% 的数据包丢失?
- flutter - 无法在 YoutubeVideoPlayer Flutter 上使用全屏(发生在 android 本机设备上)
- javascript - 如何使用 CSS 或 JavaScript 调整打印机的颜色配置文件/选项
- python - 文件夹名称中的特殊字符
- java - 错误:javax.xml.bind.JAXBContext(命令行)