nextjs 路由中间件进行身份验证 [英] nextjs route middleware for authentication
问题描述
我正在尝试找出一种适当的身份验证方式,我知道这是 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 learn 并添加 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 帮我解决了这个问题.here 可以找到解决方案,但我会引用他的话,让大家看看:
Tim from the next chat helped me solve this. Solution can be found here but I will quote him so you all can see:
- 您可以在
_app.js
getInitialProps
和 像这样重定向 - 使用示例
- _app.js 文档
我还创建了一个示例骨架模板,你可以看看.
I've also created an example skeleton template you can take a look at.
--
2021 年 7 月编辑 - 警告:这是一个过时的解决方案,尚未确认可与最新版本的 next.js 一起使用.使用骨架模板需要您自担风险.
EDIT July 2021 - WARNING: This is an outdated solution and has not been confirmed to work with the latest versions of next.js. Use skeleton template at your own risk.
这篇关于nextjs 路由中间件进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!