Node.js passport-jwt如何在cookie中发送令牌?

时间:2016-08-26 09:50:05

标签: node.js jwt passport.js

1)用户通过身份验证后,如何在Cookie中设置令牌,以便用户不会在每个请求中发送用户名密码?

2)向客户端发送令牌的理想方式是什么?

    apiRoutes.post('/authenticate', function (req, res) {
        User.findOne({
            email: req.body.email
        }, function (err, user) {
            if (err) throw err;

            if (!user) {
                res.send({ success: false, message: 'Authentication failed. User not found.' });
            } else {
                // Check if password matches
                user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                        // Create token if the password matched and no error was thrown
                        var claims = {
                            sub: user._id,
                            email:user.email,
                            iss: 'https://NodeLogin.com',
                            permissions: user.role
                        };

                        var token = jwt.sign(claims, config.secret, {
                            expiresIn: 60 // in seconds
                        });
                        res.json({ success: true, token: 'JWT ' + token });
                    } else {
                        res.send({ success: false, message: 'Authentication failed. Passwords did not match.' });
                    }
                });
            }
        });
    });

    apiRoutes.get('/dashboard',
        passport.authenticate('jwt', { session: false }), function (req, res) {
        res.send('Worked' + req.user._id + '.');
    });

2 个答案:

答案 0 :(得分:14)

你应该遵守代码:

user.comparePassword(req.body.password, function (err, isMatch) {
  if (isMatch && !err) {
    // Create token if the password matched and no error was thrown
    var claims = {
      sub: user._id,
      email:user.email,
      iss: 'https://NodeLogin.com',
      permissions: user.role
    };

    var token = jwt.sign(claims, config.secret, {
      expiresIn: 60 // in seconds
    });

    res.cookie('jwt',token); // add cookie here
    res.json({ success: true, token: 'JWT ' + token });
  } else {
    res.send({ success: false, message: 'Authentication failed. Passwords did not match.' });
  }
});

和护照配置:

var cookieExtractor = function(req) {
  var token = null;
  if (req && req.cookies) token = req.cookies['jwt'];
  return token;
};
module.exports = function(passport) {  
  var opts = {};
  opts.jwtFromRequest = cookieExtractor; // check token in cookie
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.id}, function(err, user) {
      if (err) {
        return done(err, false);
      }
      if (user) {
        done(null, user);
      } else {
        done(null, false);
      }
    });
  }));
};

它对我有用:)

答案 1 :(得分:0)

对于httpOnlysignedsecure Cookie,您可能需要使用signedCookies

const cookieExtractor = function (req) {
    let token = null;
    if (req && req.signedCookies && req.signedCookies.jwt) {
        token = req.signedCookies['jwt']['token'];
    }
    return token;
};