node.js - 如何在 cookie 中存储 jwt 并在重定向页面时将其传递给身份验证函数?

标签 node.js express jwt handlebars.js postman

我有一个使用 Postman 构建并使用 Jest 进行测试的 Node.js Express 后端。我用hbs写了一个前端,下一步就是缝合它们。但是,我仍然不断收到来 self 的身份验证函数的“请验证”错误消息,我猜这是因为我没有成功传递我的 jwt token 。

因此,在登录页面(用户/登录)上,我想使用电子邮件和密码登录,然后我想重定向到我的页面(用户/我),在其中我可以执行属于该用户的其他操作。

前端 登录页面代码:

<section class="login-bg">
        <div class="login-form">
            <p>Welcome to Task Manager, please log in!</p>
            <form class="input-group" action="/users/login" method="POST">
                <label>Email:</label>
                <input type="email" name="email" placeholder="type your email" value="{‌{user.email}}" required >
                <label>Password:</label>
                <input type="password" name="password" placeholder="type your password" value="{‌{user.password}}" required>

                <button class="button" type="submit">Log In</button>
            </form>
        </div>
    </section>

后端

在中间件/auth.js

const jwt = require('jsonwebtoken')
const User = require('../models/user')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        const user = await User.findOne({_id: decoded._id, 'tokens.token': token})

        if (!user) {
            throw new Error()
        }

        req.token = token
        req.user = user
        next()

    } catch (error) {
        res.status(401).send({error: 'Please authenticate.'})
    }
}

module.exports = auth

在 src/routers/users.js

router.post('/login', async (req, res) => {
    try {
        const user = await User.findByCredentials(req.body.email, req.body.password)
        const token = await user.generateAuthToken()
        res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })
        res.redirect('/users/me')
    } catch (error) {
        res.status(400).send()
    }
})

但是,当我在 users/me 中执行 console.log(document.cookie) 时,它显示未定义。

然后我安装了 cookie-parser 并导入到 app.js,并尝试在 src/routers/user.js 中编写这部分:

router.get('/me', auth, async (req, res) => {
    console.log('Cookies: ', req.cookies)
    try {
        res.render('me', {name: user.name})
    } catch (error) {
        res.status(500).send()
    }
})

但是这个控制台不打印任何内容,可能是因为我从身份验证中收到错误。

我的页面上还附加了一个 js 文件,但我不知道是否可以这样写,可能是错误的:

const userToken = document.cookie.jwt.token

fetch('/users/me', {
    method: 'POST',
    headers: {
     'Authorization': 'Bearer ' + userToken
    }
})
.then(res => res.json())
.then(data => { console.log(data) })
.catch(err => { console.log(err) })

然后在网络/ header 中,我有

请求网址:

http://localhost:3000/users/login

请求方式:

发布

状态代码:

找到 302 条

远程地址:

推荐人政策:

降级时无引荐来源网址

响应 header

连接:

保持事件状态

内容长度:

62

内容类型:

文本/html;字符集=utf-8

日期:

2019 年 6 月 7 日星期五 18:41:47 GMT

地点:

/用户/我

设置 Cookie:

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5 OAySyeH25fs;最大年龄=3600;路径=/;过期=2019 年 6 月 7 日星期五 19:41:47 GMT;仅 Http;安全

变化:

接受

X-Powered-By:

express

没有请求cookie,只有响应cookie。我不确定这些意味着什么...@_@

我想传递 jwt 来成功登录并正确渲染我的页面,我该怎么做?

最佳答案

您的 jwt token cookie 不起作用,因为它在以下代码中声明了标志 secure: true:

res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })

这导致HTTP响应中的Secure标志,表明该cookie仅在HTTPS环境下可用:

Set-Cookie:
jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH25fs; 
Max-Age=3600; Path=/; 
Expires=Fri, 07 Jun 2019 19:41:47 GMT; HttpOnly; Secure

由于您的请求 URL 使用 HTTP (http://localhost:3000/users/login),浏览器将忽略 cookie。

关于node.js - 如何在 cookie 中存储 jwt 并在重定向页面时将其传递给身份验证函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56524264/

相关文章:

node.js - CouchDB 响应失败的方式有哪些?

express - 如何分发使用 Electron、Node.js 和 Python 构建的桌面应用程序

java - 如何用UTC过期时间验证JWT?

javascript - 为什么我不能将两个数组与 "includes"进行比较?

javascript - 在构造函数中,将构造的对象设置为另一个

javascript - 环回/ express : How to redirect to URL inside a remoteMethod?

javascript - MongoDB Stitch JWT 自定义身份验证 : valid UID required (between 1 and 128 characters)

python - OTP 验证时 JWT token 不匹配

node.js - 如何对通过管道 readStream 传递的内容进行 gZip

node.js - 为什么 Restful 不能将 body 传递到数据库中