nextjs路由中间件进行身份验证 [英] nextjs route middleware for authentication

查看:924
本文介绍了nextjs路由中间件进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出进行身份验证的适当方法,我知道这是 GitHub问题页面.

I'm trying to figure out an appropriate way of doing authentication, which I know is a touchy subject on the GitHub issue page.

我的身份验证很简单.我将JWT令牌存储在会话中.我将其发送到其他服务器以供批准.如果返回true,则继续进行;如果返回false,则清除会话并将其发送到主页.

My authentication is simple. I store a JWT token in the session. I send it to a different server for approval. If I get back true, we keep going, if I get back false, it clears the session and puts sends them to the main page.

在我的server.js文件中,我有以下内容(注意-我正在使用 nextjs学习,只添加isAuthenticated):

In my server.js file I have the following (note- I am using the example from nextjs learn and just adding isAuthenticated):

function isAuthenticated(req, res, next) {
  //checks go here

  //if (req.user.authenticated)
   // return next();

  // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
  res.redirect('/');
}

server.get('/p/:id', isAuthenticated, (req, res) => {
  const actualPage = '/post'
  const queryParams = { id: req.params.id }
  app.render(req, res, actualPage, queryParams)
})

这按设计工作.如果刷新页面/p/123,它将重定向到/.但是,如果我通过next/link href转到那里,则不会.我相信是因为此时它不在使用express,而是next的自定义路由.

This works as designed. If I refresh the page /p/123, it will redirect to the /. However, if I go there via a next/link href, it doesn't. Which I believe is because it's not using express at this point but next's custom routing.

有没有一种方法可以对每笔未通过Express的next/link进行检查,以确保用户已登录?

Is there a way I can bake in a check for every single next/link that doesn't go through express so that I can make sure the user is logged in?

推荐答案

Tim帮助我解决了这个问题.可以找到解决方法此处,但我会引用他,这样所有人都可以看到:

Tim from the next chat helped me solve this. Solution can be found here but I will quote him so you all can see:

  • You can do the check in _app.js getInitialProps and redirect like this
  • Example of how to use it
  • _app.js documentation

我还创建了一个示例骨架模板,您可以看一下.

I've also created an example skeleton template you can take a look at.

这篇关于nextjs路由中间件进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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