【问题标题】:Node.js passport-jwt how to send token in a cookie?Node.js passport-jwt 如何在 cookie 中发送令牌?
【发布时间】:2017-01-02 22:56:54
【问题描述】:

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

【问题讨论】:

    标签: node.js jwt passport.js


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你应该遵循代码:

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

      它对我有用:)

      【讨论】:

      • 很高兴为您提供帮助:)
      • 出于兴趣 - 为什么在 Passport 验证时令牌没有过期? 60 秒的过期时间肯定是个问题吗?
      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2020-12-14
      • 2017-03-04
      • 2019-10-23
      • 2020-08-21
      • 2020-10-01
      • 2018-06-08
      • 2018-07-12
      相关资源
      最近更新 更多