如果我使用httpOnly cookie,我如何构建用于保护路由的HOC



我将我的令牌存储在httpOnly cookie中,但当我想构建一个HOC来保护路由时,无法直接在组件内部访问cookie,我必须在服务器端进行,我试着做这样的事情,但不起作用:

import Cookie from "cookies";
const withAuth = (Page) => {
Page.getServerSideProps = async ({ req, res }) => {
const cookie = new Cookie(req, res);
const token = cookie.get("token");
if (!token)
return {
redirect: {
permanent: false,
destination: "/login",
},
};
return {
props: {
token,
},
};
};
return Page;
};
export default withAuth;

getServerSideProps函数仅适用于页面,而不适用于组件

下面的代码片段应该可以帮助您创建用于身份验证的HOC。这个例子使用了闭包的概念。我把这个叫做withAdministrator.jsx

// withAdministrator.jsx
export default (GetServerSidePropsFunction) => async (ctx) => {
// 1. Check if there is a token.
const token = ctx.req.cookies?.jwt || null;
// 2. Perform an authorized HTTP GET request to the private API to get user data.
// In here, assume that 'getAuth' is a function to perform authorized GET request using the token value in the 'Authorization' header.
const { data } = await getAuth(`${process.env.PRIVATE_API_URL}/api/v1/users/user`, token);
// 3. If there is no user, or the user is not an admin, then redirect to unauthorized.
if (!data || data.role !== 'admin') {
return {
redirect: {
destination: '/unauthorized',
permanent: false,
},
};
}
// 4. Return via closure: 'GetServerSidePropsFunction'.
return await GetServerSidePropsFunction(ctx);
};

你会这样称呼它的。假设您想要访问/admin路由。

export const getServerSideProps = withAdministrator(() => {
return {
props: {},
};
});
const Admin = () => {
return (
<YourComponent />
);
};

您可以在返回的函数中执行任何您想要的操作。例如,您可能希望在对用户进行身份验证后获取数据。

进一步阅读:Next.js.中的数据提取

最新更新