JSON Web令牌策略

时间:2018-10-21 04:02:24

标签: node.js express jwt passport.js

这是提取标题的通行证功能。我正在使用fromAuthHeaderWithScheme之一,我已经尝试过使用不记名令牌的fromAuthHeaderAsBearerToken。无论如何,我都无法使它正常工作?

const JwtStrategy = require('passport-jwt').Strategy,
      ExtractJwt = require('passport-jwt').ExtractJwt,
      User = require('../models/user'),
      Config = require('../config/database');


    module.exports = function(passport) {

      let opts = {};

      opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
      opts.secretOrKey = Config.secret;
      //Code only comes until here. 
      passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        console.log(jwt_payload);//Code never reaches here.
        User.getByUserId({
          id: jwt_payload._id
        }, function(err, user) {
          if (err) {
            return done(err, false);
          }
          if (user) {
            return done(null, user);
          } else {
            return done(null, false);
          }
        });
      }));


    }

接下来是我的getUserById函数

module.exports.getByUserId = function(id, cb) {
  User.findById(id, cb)
}

接下来,是上面两个被称为的地方:

router.post('/login', function(req, res) {
  let username = req.body.username;
  password = req.body.password;

  User.getByUserName(username, function(err, user) {
    if (err) {
      throw err;
    }
    if (!user) {
      return res.json({
        success: "false",
        msg: "User not found"
      })
    }
    //if found compareUser to regiestred one
    User.comparePassword(password, user.password, function(err, isMatched) {
      if (err) {
        throw err;
      }
      if (isMatched) {
        const token = jwt.sign(user.toJSON(), CONFIG.secret, {
          expiresIn: 3600 /*Logout in 1 hour*/
        });

        res.json({
          success: "true",
          token: 'JWT ' + token,
          user: user._id,
          email: user.email,
          username: user.username,
        });
      } else {
        return res.json({
          success: "false",
          msg: " Password not Matched"
        });
      }
    });
  });
});

如果需要查看,这些是comparePassword和getUserByName:

module.exports.comparePassword = function(typedPassword, hash, cb) {
  bcrypt.compare(typedPassword, hash, (err, isMatched) => {
    if (err) {
      throw err;
    }
    return cb(null, isMatched);
  })
};

module.exports.getByUserName = function(username, cb) {
  const query = {
    username: username
  }
  User.findOne(query, cb);
}

每个地方的密钥都是相同的,这不是问题。我似乎无法弄清楚问题所在。

router.get("/profile", passport.authenticate('jwt', {
  session: false
}, function(req, res, next) {
  res.json({
    success: true,
    message: "This is user profile",
    user: req.user
  });
}));

现在,以上是我如何使用邮递员身份验证并将身份验证请求发送为内容类型“授权”和令牌的方法。包裹,你们中的任何人都想知道,我已经通过承载方案尝试了“ bearer” +令牌。

1 个答案:

答案 0 :(得分:0)

我将上面发布的第一个代码块更改为此

 const JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt,
        keys = require('./keys'),
        mongoose = require('mongoose'),
        User = require('../models/User');

    const opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken('Bearer');
    opts.secretOrKey = keys.secretOrKey;


    module.exports = passport => {
        passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
            User.findOne({ id: jwt_payload.sub }, (err, user) => {
                User.findById(jwt_payload.id)
                    .then(user => {
                        if (user) {
                            return done(null, user);
                        }
                        return done(null, false);
                    })
                    .catch(err => console.log(err));
            });
        }))
    };

第二个步骤。基本上将令牌从“ JWT”更改为“ Bearer”。

router.post('/login', (req, res) => {
    const email = req.body.email, password = req.body.password;
    User.findOne({ email: email })
        .then(user => {
            if (!user) {
                res.status(404).json({ msg: 'User not found' })
            }
            //Check password
            bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if (isMatch) {
                        //User found
                        //Create Jwt Payload
                        const payload = {
                            id: user.id,
                            name: user.name,
                            avatar: user.avatar
                        }

                        jwt.sign(
                            payload,
                            keys.secretOrKey,
                            { expiresIn: 3600 },
                            (err, token) => {
                                res.json({
                                    success: true,
                                    token: 'Bearer ' + token
                                });
                            });
                    } else {
                        return res.status(400).json({ password: 'Password do not match' })
                    }
                })
            // .catch(err => console.log(err));

        })
});

现在为我工作。