如何在后端使用节点 js 在客户端存储令牌?

How to store tokens on the client side using node js on backend?

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

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

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

你可以做到这一点

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