重定向页面时如何将jwt存储在cookie中并将其传递给身份验证功能? [英] How to store jwt in cookie and pass it to authentication function when redirecting a page?

查看:13
本文介绍了重定向页面时如何将jwt存储在cookie中并将其传递给身份验证功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Postman 构建并使用 Jest 测试的 node.js express 后端.我用 hbs 写了一个前端,下一步是缝合它们.但是,我仍然不断收到来自我的身份验证函数的请验证"错误消息,我猜这是因为我没有成功传递我的 jwt 令牌.

I have a node.js express backend built with Postman and tested with Jest. I wrote a front end with hbs and the next step is to stitch them. However I still keep getting "please authenticate" error message that's from my auth function, which I guess is because I'm not successfully passing my jwt token.

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

So on login page (users/login) I want to login with email and password then I want to redirect to me page(users/me) where I can perform other stuff that belongs to this user.

前端登录页面代码:

<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中

in middleware/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 中

in 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) 时,它显示未定义.

However, when I do console.log(document.cookie) in users/me it says undefined.

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

Then I have the cookie-parser installed and import to app.js, and try to write this part in src/routers/users.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()
    }
})

但是这个控制台不打印任何东西,可能是因为我从 auth 得到错误.

but this console doesn't print anything, probably cos I am getting error from auth.

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

I also have a a js file attached to me page but I have no clue if I could write this way, probably wrong:

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) })

然后在网络/标题中,我有

then in the Network / Headers, I have

请求网址:

http://localhost:3000/users/login

请求方法:

发布

状态码:

302 找到

远程地址:

推荐人政策:

降级时无推荐人

响应标头

连接:

保持活力

内容长度:

62

内容类型:

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

text/html; charset=utf-8

日期:

格林威治标准时间 2019 年 6 月 7 日星期五 18:41:47

Fri, 07 Jun 2019 18:41:47 GMT

地点:

/用户/我

设置 Cookie:

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH2;最大年龄=3600;路径=/;过期=格林威治标准时间 2019 年 6 月 7 日星期五 19:41:47;仅http;安全

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

变化:

接受

X-Powered-By:

X-Powered-By:

快递

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

There is no request cookies, only response cookies. I am not sure what those means...@_@

我想通过 jwt 成功登录并正确呈现 me 页面,我该怎么做?

I want to pass the jwt to successfully login and render the me page properly, how could I do that?

推荐答案

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

Your jwt token cookie does not work because it declares flag secure: true in the following code:

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

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

which lead to Secure flag in HTTP response, indicating this cookie is only available under HTTPS environment:

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.

As your request URL is using HTTP (http://localhost:3000/users/login), the cookie would be ignored by browser.

这篇关于重定向页面时如何将jwt存储在cookie中并将其传递给身份验证功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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