【问题标题】:How to store tokens on the client side using node js on backend? [closed]如何在后端使用节点 js 在客户端存储令牌? [关闭]
【发布时间】:2020-01-10 23:15:02
【问题描述】:

我使用 passport.js 进行本地身份验证,使用 express-session 管理用户会话,但 express-session 将 cookie 存储在客户端。由于 cookie 的安全性较低,我想在客户端发送和接收 jwt 令牌,但我不知道该怎么做。 我正在使用 mongodb 作为数据库,表达框架和节点 js

【问题讨论】:

    标签: node.js mongodb express jwt passport.js


    【解决方案1】:

    你可以这样做

    在 node.js 中

    verifyToken = (req, res, next) => {
        let token = req.headers['x-access-token'];
    
        if (!token) {
            return res.status(403).send({
                auth: false, message: 'No token provided.'
            });
        }
    
        jwt.verify(token, config.secret, (err, decoded) => {
            if (err) {
                return res.status(500).send({
                    auth: false,
                    message: 'Fail to Authentication. Error -> ' + err
                });
            }
            req.userId = decoded.id;
            next();
        });
    }
    

    然后将其添加到您的路由器

    var token = jwt.sign({ id: user.id }, config.secret, {
            expiresIn: 86400 // expires in 24 hours
        });
        res.status(200).send({ auth: true, accessToken: token });
    

    客户端

    const data = { username, password }
        await axios.post(*usl, data, {
        }).then((response) => {
            localStorage.setItem('token', response.data.accessToken)
    }, (error) => { console.log('error', error) });
    

    【讨论】:

      【解决方案2】:

      express-session 有很多不同的存储解决方案可以找到here

      例如,您可以使用 MongoDB 来存储会话数据。

      【讨论】:

        猜你喜欢
        • 2017-11-30
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 2012-10-08
        • 2020-12-21
        • 1970-01-01
        • 2019-04-21
        • 2016-06-01
        相关资源
        最近更新 更多