将JWT保存在cookie或本地存储中(node / angular 2网站)

时间:2017-05-07 16:16:17

标签: javascript node.js angular jwt

我知道jwt可以保存在本地存储或cookie中。但我无法在网上找到一份好的材料来获取指示。如何指示服务器识别用户以用于将来的会话。

    //authenticating users by username
router.route('/authentication').post(function(req, res) {
    User.findOne({username : req.body.username}, function(err, user){
        if (err) throw err;
        if (!user) {
            res.json({ success: false, message: 'Authentication failed. User not found.' });
        } else if (user) {

            // check if password matches
            if (user.password != req.body.password) {
                res.json({ success: false, message: 'Authentication failed. Wrong password.' });
            } else {

                // if user is found and password is right
                // create a token
                var token = jwt.sign({usern : user.username}, app.get('superSecret'), {
                //expiresInMinutes: 1440 // expires in 24 hours
                });
                res.cookie('auth',token);
                // return the information including token as JSON
                res.setHeader('token', token);
                res.json({
                success: true,
                message: 'Enjoy your token!',
                token: token
                });
            }   
        }
    });
})

app.use('/api', router);

0 个答案:

没有答案