在nextJS中为cookie创建HOC(高阶组件)
所以我在 Next.js 应用程序中创建身份验证逻辑。我创建了/api/auth/login处理请求的页面,如果用户的数据良好,我将httpOnly使用 JWT 令牌创建一个cookie 并将一些数据返回到前端。这部分工作正常,但我需要某种方法来保护某些页面,以便只有登录的用户才能访问它们,而我在为此创建 HOC 时遇到了问题。
我看到的最好的方法是使用,getInitialProps但在 Next.js 网站上它说我不应该再使用它,所以我想使用getServerSideProps但那也不起作用,或者我可能做错了什么。
这是我的 HOC 代码:(cookie 存储在“userToken”名称下)
import React from 'react';
const jwt = require('jsonwebtoken');
const RequireAuthentication = (WrappedComponent) => {
return WrappedComponent;
};
export async function getServerSideProps({req,res}) {
const token = req.cookies.userToken || null;
// no token so i take user to login page
if (!token) {
res.statusCode = 302;
res.setHeader('Location', '/admin/login')
return {props: {}}
} else {
// we have token so i return nothing without changing location
return;
}
}
export default RequireAuthentication;
如果您对如何在 Next.js 中使用 cookie 处理身份验证有任何其他想法,我将不胜感激,因为我是服务器端渲染 react/auth 的新手。
回答
您应该从getServerSideProps.
例如,您可以有一个高阶函数,它会接受另一个函数(您的getServerSideProps),如果userToken未设置,则会重定向到您的登录页面。
export function requireAuthentication(gssp) {
return async (context) => {
const { req, res } = context;
const token = getUserToken(req.headers.cookie) // Add logic to extract token from `req.headers.cookie`
if (!token) {
// Redirect to login page
return {
redirect: {
destination: '/about',
statusCode: 302
}
};
}
return await gssp(context); // Continue on to call `getServerSideProps` logic
}
}
然后,您将通过包装getServerSideProps函数在您的页面中使用它。
// pages/index.js (or some other page)
export const getServerSideProps = requireAuthentication(context => {
// Your normal `getServerSideProps` code here
})