【问题标题】:How to implement JWT with Passport on this example在这个例子中如何使用 Passport 实现 JWT
【发布时间】:2019-01-08 21:37:46
【问题描述】:

我正在设置一个服务器,并希望在用户登录后用 JWT 响应用户。我现在正在使用护照,但不知道在这种情况下如何实现验证 JWT。

这里是登录路径:

  app.route('/login')
    .get(users.renderLogin)
    .post(users.auth);

当用户登录时,我发送他的 Token 和一些信息:

exports.auth = function (req, res, next){

  passport.authenticate('local', {session: false}, (err, user, info) => {

    if (err) { return next(err); }
      console.log(err);

    if (!user) { return res.redirect('/login'); }

    req.logIn(user, function(err) {
      if (err) { return next(err); }

      // Loged in 
      const userInfo = {
        username: user.username,
        name: user.name,
        age: user.age,
        groupid: user.groupid,
        email: user.email,
      }
      const token = jwt.sign(userInfo, process.env.JWT_SEC);
      res.json({
        user,
        token
      })
      // res.redirect('/');
    });
  })(req, res, next);
};

之后,我需要在每个用户调用中验证 JWT 令牌。有人有什么建议吗?

谢谢

【问题讨论】:

  • 我建议你使用JWT策略而不是本地的passportjs.org/packages/passport-jwt。就我个人而言,我认为 PassportJS 有点过时,并且为呈现 HTML 的服务器设计得比纯 API 服务器更好,但它仍然很有可能让它与纯 API 服务器一起工作。

标签: node.js authentication jwt passport.js


【解决方案1】:

来自passport

Passport 的唯一目的是验证请求,它通过一组称为策略的可扩展插件来完成。

另外来自passport-local

本地身份验证策略使用用户名和密码对用户进行身份验证。该策略需要一个验证回调,它接受这些凭据并为用户提供完成的调用。

因此,passport 的本地策略只会验证同时提供usernamepassword 的请求。因此,客户端每次想要访问应用程序时都必须发送这些凭据。

因此,要使用 Web 令牌对请求进行身份验证,您需要提供一个设置 JWT 的登录过程。 (然后客户端只需发送令牌,无需每次都存储和传输明文密码)

为此,npm 上有很多可用的软件包。我个人使用并推荐jsonwebtoken

用户模型

假设你有一个用户模型比如

const UserSchema = new mongoose.Schema({
email: {
    type: String,
    unique: true,
    required: true,
    maxlength: 254,
    trim: true,
    match: /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+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%7C%5B1-9%5D%3F%5B0-9%5D)%7C%5Ba-z0-9-%5D*%5Ba-z0-9%5D%3A(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21-%5Cx5a%5Cx53-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)%2B)%5C%5D)
    // SFSM :           https://en.wikipedia.org/wiki/Finite-state_machine
    // Xcrowzz' note :  Seems to work for 99.99% of email addresses, containing either local, DNS zone and/or IPv4/v6 addresses.
    // Xcrowzz' note :  Regex can be targeted for Catastrophic Backtracking (https://www.regular-expressions.info/catastrophic.html) ; See https://www.npmjs.com/package/vuln-regex-detector to check them before someone DDOS your app.
},
password: {
    type: String,
    required: true,
    minlength: 8,
    maxlength: 254,
    select: false
},
username: {
    type: String,
    required: false,
    unique: true,
    maxlength: 254
}
});
module.exports = mongoose.model('User', UserSchema);

用户控制器

现在,是时候实现 JWT 生成和签名了,这应该在用户成功登录时完成。也就是说,当 body 请求中提供的 usernamepassword 都与 DB 匹配时(不要忘记将明文密码与使用bcrypt.compare 存储的哈希值进行比较)

const jwt = require('jsonwebtoken');
[...]
exports.logUser = async (req, res) => {
    if (!req.body.email || !req.body.password) { return res.status(400).send('Bad Request');}
    else {
        await UserModel.findOne({ email: req.body.email }, async (err, user) => {
            if (err) return res.status(500).send('Internal Server Error');
            if (!user) return res.status(404).send('Not Found');

            let passwordIsValid = await bcrypt.compare(req.body.password, user.password);
            if (passwordIsValid) {
                let token = jwt.sign({ id: user._id }, secret, { expiresIn: 86400 }); // 24 Hours
                return res.status(200).send({ auth : true, token: token });
            } else {
                return res.status(404).send('Not Found');
            }
        }).select('+password'); // Overrides model's 'select:false' property of the password model's property in order to compare it with given plaintext pwd.
    }
};

注意事项

let token = jwt.sign({ id: user._id }, secret, { expiresIn: 86400 }); 基于id 和先前定义的secret 创建令牌,该字符串应该是一个非常长且随机的字符串,令牌的整体完整性和安全性可能会受到弱secret 的影响。

这是 JWT 最基本的配置,一些研究会证明你的代码还没有准备好生产。但在你的情况下,这样就可以了。

身份验证控制器

最后,您必须设计身份验证中间件,将提供的令牌与之前签名的令牌进行比较。再一次,它使用secret 来比较它们。

const secret = (process.env.TokenSuperSecret) ? 
process.env.TokenSuperSecret : 'SuperSecret';
const jwt = require('jsonwebtoken');
const passport = require('passport');
const CustomStrategy = require('passport-custom');

passport.use('jwt', new CustomStrategy(async (req, callback, err) => {
const token = req.headers['x-access-token'];
if (!token) return callback(err);
await jwt.verify(token, secret, (err, decoded) => {
    if (err) return callback(err);
    req.userId = decoded.id;
    callback(null, req);
    });
}));

exports.isAuthenticated = passport.authenticate('jwt', {
  session: false
}, null);

注意事项

jwt.verify(token, secret, (err, decoded) => {} 返回一个包含decoded userId 的承诺(您在登录过程中使用jwt.sign 编码)。随意将它传递给您的中间件,以了解当前正在执行请求的用户。

久等了,感谢所有的鱼!

【讨论】:

  • 我有一个使用 bcrypt 进行比较的模型,就像你所建议的那样。我可以在这个用户模型中实现 JWT 吗?这是一个好习惯吗?
  • 我已更新我的答案以使用基本用户模型。
  • 实际上,我真的不明白如何在我的情况下使用它。我将编辑我的问题以使其更清楚
  • 问题是你没有像我在 controllers/users.js @ let token = jwt.sign({ id: user._id }, secret, { expiresIn: 86400 }); // 24 Hours 中那样生成 jwt。最后,您需要使用 jwt.verify 在自定义 Passport 策略 @controllers/auth.js (或我假设的 passport-jwt 包)中解码该令牌
  • 有效!我使用了您所建议的部分内容谢谢您的宝贵时间
猜你喜欢
  • 2018-03-08
  • 2020-10-21
  • 2017-07-11
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多