在 nextJS 中为 cookie 创建 HOC(高阶组件) [英] Creating a HOC (higher order component) for cookies in nextJS
问题描述
所以我在 Next.js 应用程序中创建身份验证逻辑.我创建了 /api/auth/login
页面,在其中处理请求,如果用户数据良好,我将使用 JWT 令牌创建一个 httpOnly
cookie 并将一些数据返回到前端.这部分工作正常,但我需要某种方法来保护某些页面,以便只有登录的用户才能访问它们,而我在为此创建 HOC 时遇到了问题.
So I'm creating authentication logic in my Next.js app. I created /api/auth/login
page where I handle request and if user's data is good, I'm creating a httpOnly
cookie with JWT token and returning some data to frontend. That part works fine but I need some way to protect some pages so only the logged users can access them and I have problem with creating a HOC for that.
我看到的最好方法是使用 getInitialProps
但在 Next.js 站点上它说我不应该再使用它,所以我想使用 getServerSideProps
但是这也不起作用,或者我可能做错了什么.
The best way I saw is to use getInitialProps
but on Next.js site it says that I shouldn't use it anymore, so I thought about using getServerSideProps
but that doesn't work either or I'm probably doing something wrong.
这是我的 HOC 代码:(cookie 存储在userToken"名称下)
This is my HOC code: (cookie are stored under "userToken" name)
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 的新手.
If you have any other ideas how to handle auth in Next.js with cookies I would be grateful for help because I'm new to the server side rendering react/auth.
推荐答案
您应该从 getServerSideProps
中分离并提取您的身份验证逻辑.
You should separate and extract your authentication logic from getServerSideProps
.
例如,您可以有一个高阶函数,它可以接受另一个函数(您的 getServerSideProps
),并且如果 userToken
不是,则会重定向到您的登录页面设置.
For instance, you could have a higher-order function that would accept another function (your getServerSideProps
) and would redirect to your login page if the userToken
wasn't set.
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
函数在您的页面中使用它.
You would then use it in your page by wrapping the getServerSideProps
function.
// pages/index.js (or some other page)
export const getServerSideProps = requireAuthentication(context => {
// Your normal `getServerSideProps` code here
})
这篇关于在 nextJS 中为 cookie 创建 HOC(高阶组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!