带有 node-jwt-simple 的本地护照 [英] passport-local with node-jwt-simple

查看:15
本文介绍了带有 node-jwt-simple 的本地护照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何结合本地护照以在成功验证时返回 JWT 令牌?

How can I combine passport-local to return a JWT token on successful authentication?

我想使用 node-jwt-simple 并查看 passport.js 我不知道该怎么做.

I want to use node-jwt-simple and looking at passport.js I am not sure how to go about.

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

调用 done() 时是否可以返回令牌?像这样的东西......(只是伪代码)

Is it possible to return the token when calling done() ? Something like this... (just pseudo code)

if(User.validCredentials(username, password)) {
  var token = jwt.encode({username: username}, tokenSecret);
  done(null, {token : token}); //is this possible?
}

如果没有,我该如何退回令牌?

If not, how can I return the token?

推荐答案

我想通了!

首先,您需要实施正确的策略.在我的例子中是 LocalStrategy,你需要提供你的验证逻辑.例如,让我们使用本地护照中的那个.

First of all you need to implement the correct strategy. In my case LocalStrategy, and you need to provide your validation logic. For example sake let's use the one in passport-local.

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

您提供的验证回调 function(username, password, done) 将负责查找您的用户并检查密码是否匹配(超出问题和我的答案的范围)

the verify call back you provide function(username, password, done) will take care of finding your user and checking if the password matches (beyond the scope of the question and my answer)

passport.js 需要几个部分来让它工作,一个是你在策略中返回用户.我试图改变那部分代码,这是错误的.如果验证失败,回调需要 false,如果成功则返回 object(验证用户).

passport.js expects several pieces for it to work, one is that you return the user in the strategy. I was trying to change that part of the code, and that was wrong. The callback expects false if the validation fails and an object (the validated user) if you are successful.

现在....如何集成 JWT?

Now.... how to integrate JWT?

在您的登录路径中,您必须处理成功的身份验证或不成功的身份验证.在这里,您需要添加 JWT 令牌创建.像这样:

In your login route you will have to handle a successful auth or an unsuccessful one. And it is here that you need to add the JWT token creation. Like so:

(请记住禁用会话,否则您将必须实现序列化和反序列化功能.如果您不持久化会话,则不需要这些,如果您使用基于令牌的身份验证,则不需要)

(remember to disable the session, otherwise you will have to implement the serialize and deserialize functions. And you don't need those if you are not persisting the session, which you are not if you are using a token based auth)

来自本地护照示例:(添加了 JWT 令牌)

From passport-local examples: (with the JWT token added)

// POST /login
//   This is an alternative implementation that uses a custom callback to
//   achieve the same functionality.
app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {
      return res.json(401, { error: 'message' });
    }

    //user has authenticated correctly thus we create a JWT token 
    var token = jwt.encode({ username: 'somedata'}, tokenSecret);
    res.json({ token : token });

  })(req, res, next);
});

就是这样!现在,当您调用/login 并 POST 用户名和密码(应始终通过 SSL)时,上面的第一个代码片段将尝试根据您提供的用户名查找用户,然后检查密码是否匹配(当然您需要更改它以满足您的需要).

And that is it! Now when you call /login and POST username and password (which should always be over SSL) the first code snippet above will try to find a user based on the username you provided and then check that the password matches (Of course you will need to change that to suit your needs).

之后,您的登录路由将被调用,您可以在此处处理返回错误或有效令牌.

After that your login route will be called and there you can take care of returning an error or a valid token.

希望这会对某人有所帮助.如果我犯了任何错误或忘记了什么,请告诉我.

Hope this will help someone. And if I have made any mistakes or forgot something let me know.

这篇关于带有 node-jwt-simple 的本地护照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆