如何将JWT令牌从客户端发送回服务器?

时间:2020-05-30 01:02:50

标签: node.js jwt frontend

所以目前我有一个后端API端点api / user / login。当用户成功登录后,我将response.header发送回客户端,并且在此标头中,我包括一个JWT令牌,如下所示:

router.post('/login', async (request, response) => {

    // validate 
    const {error} = loginValidation(request.body)
    if (error) return response.status(400).send(error.details[0].message)


    const {email, password} = request.body


    // check if email doesn't exist
    const user = await pool.query('SELECT id, email, password FROM users WHERE email = $1 LIMIT 1', [email])
    if(user.rowCount == 0) return response.status(400).send('Wrong email or password')

    // password is correct; move on to validating password
    const id = user.rows[0].id
    const storedEmail = user.rows[0].email
    const storedPassword = user.rows[0].password
    const validPass = await bcrypt.compare(request.body.password, storedPassword)
    if(!validPass) return response.status(400).send('Wrong email or password')

    // create and send token to client
    const token = jwt.sign({_id: id}, "SOMESECRET")
    response.header('auth-token', token).send(token)


})

在JWT有效负载中,我仅存储用户ID,当用户尝试访问受保护的路由时,我会从标头中的JWT从数据库中查询用户。

我的问题是,在客户端上,一旦我收到JWT,如何保存它,然后在以后的api请求中将其作为标头发送?

此外,我是否应该将JWT存储为httpOnly cookie?然后如何在其他客户端(例如iOS应用)中使用我的API端点?

我这样验证:

module.exports = function (request, response, next){
    const token = request.header('auth-token')
    if(!token) return response.status(401).send('Access Denied')

    try {
        const verifed = jwt.verify(token, "SOMESECRET")
        request.user = verifed
        next()
    } catch(error){
        response.status(400).send('Invalid Token')
    }
}

0 个答案:

没有答案