program story

node-jwt-simple이있는 passport-local

inputbox 2020. 9. 12. 10:00
반응형

node-jwt-simple이있는 passport-local


성공적인 인증에서 JWT 토큰을 반환하기 위해 passport-local을 결합하려면 어떻게해야합니까?

node-jwt-simple 을 사용 하고 passport.js를 보고 싶습니다. 어떻게해야할지 모르겠습니다.

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 ()을 호출 할 때 토큰을 반환 할 수 있습니까? 이와 같은 것 ... (그냥 의사 코드)

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

그렇지 않은 경우 토큰을 어떻게 반환 할 수 있습니까?


나는 그것을 알아!

우선 올바른 전략을 구현해야합니다. 제 경우에는 LocalStrategy이며 유효성 검사 논리를 제공해야합니다. 예를 들어 여권 로컬에서 사용합시다.

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)은 사용자를 찾고 비밀번호가 일치하는지 확인합니다 (질문 및 내 답변의 범위를 벗어남).

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.

Now.... how to integrate 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)

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

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.


This is a great solution, I just want to add this:

var expressJwt = require('express-jwt');

app.use('/api', expressJwt({secret: secret}));

I like to use "express-jwt" to validate the token.

btw: this article is great to learn how to handle the token in the client side, using Angular, in order to send it back with every request

https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/


Here's a boiler-plate I'm working on for specifically using api tokens only (no sessions...not that session are bad of course; just we're using token approach): https://github.com/roblevintennis/passport-api-tokens

참고URL : https://stackoverflow.com/questions/20228572/passport-local-with-node-jwt-simple

반응형