web-dev-qa-db-ja.com

Node.js passport-jwt cookieでトークンを送信する方法は?

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 + '.');
    });
11
Vaibhav Ramteke

あなたはコードに従うべきです:

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

それは私のために働いています:)

19
Chris Nguyen