在Next.js中创建用于身份验证的特殊(高阶组件) [英] Create a HOC (higher order component) for authentication in Next.js

查看:24
本文介绍了在Next.js中创建用于身份验证的特殊(高阶组件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在我的Next.js应用程序中创建身份验证逻辑。我创建了处理请求的/api/auth/login页面,如果用户数据良好,我将创建一个带有JWT令牌的httpOnlycookie,并将一些数据返回到前端。该部分工作正常,但我需要一些方法来保护某些页面,以便只有登录的用户才能访问它们,而我在为此创建即席时遇到问题。

我看到的最好的方法是使用getInitialProps,但在Next.js站点上它说我不应该再使用它,所以我考虑使用getServerSideProps,但这也不起作用,或者我可能做错了什么。

以下是我的即席代码: (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;

如果您有任何其他想法如何使用Cookie处理Next.js中的auth,我将不胜感激,因为我对服务器端呈现reaction/auth还不熟悉。

推荐答案

您应该将getServerSideProps中的身份验证逻辑分离并提取到可重用的高阶函数中。

例如,您可以使用以下函数接受其他函数(您的getServerSideProps),如果未设置userToken,则会重定向到您的登录页。

export function requireAuthentication(gssp) {
    return async (context) => {
        const { req, res } = context;
        const token = req.cookies.userToken;

        if (!token) {
            // Redirect to login page
            return {
                redirect: {
                    destination: '/admin/login',
                    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
})

这篇关于在Next.js中创建用于身份验证的特殊(高阶组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆