Cloid J. Green
Cloid J. Green

Reputation: 129

JSONWebTokens with express-jwt VS passport-jwt

The express-jwt package allows tremendous flexibility in creating multiple authentication options on login( i.e. local storage or social media OAuth or OpenID providers, etc. ) and then protecting the application with JWT.

The express-jwt configuration in particular i.e.

app.use(expressJwt({ secret: jwtSecret}).unless({path:['/login']}));

shows the way.

The question is: many of the sites I want to use for login alternatives are most easily accessed through passport.js. Passport-jwt seems to use the jsonwebtokens.js module under the hood so is there a way of configuring passport-jwt with the same flexibility that can be obtained with jsonwebtokens.js and express-jwt.js individually?

Upvotes: 10

Views: 7389

Answers (1)

user6144056
user6144056

Reputation:

Yes there is. Passport has many configurations, what it terms strategies. One of those is passport-jwt: https://github.com/themikenicholson/passport-jwt

Here is a decent guide to use it with an API server: http://slatepeak.com/guides/building-a-software-as-a-service-saas-startup-pt-2/

Here is an example with a basic express app config assumed.

// init express app as normal..
var app = express();
// dependancies
var passport = require('passport');
var jwt = require('jwt-simple');
var User = require('path/to/your/db/model'); // eg. mongo
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
// configure passport jwt strategy
var JwtStrategy = require('passport-jwt').Strategy;
module.exports = function(passport) {
  // JSON Web Token Strategy
  passport.use(new JwtStrategy({ secretOrKey: 'secret' }, 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);
      });
  }));
};
// now have an authentication route
app.post('/admin/authenticate', function(req, res) {
  User.findOne({
    email: req.body.email
  }, function(err, user) {
    // create jwt token
    var token = jwt.encode(user, 'secret');
    if (err) {
      res.send({success: false, msg: 'error'});
    } else {
      res.json({success: true, token: 'JWT ' + token});
    }  
  });
});
// finally require passport strategy to secure certain routes..
app.get('/admin/getsomedata', passport.authenticate('jwt', {session: false}), successFunction);

To answer your question - in my experience yes I think it offers a lot flexibility like express-jwt, if not more, and can be abstracted from your main code easily too.

Upvotes: 6

Related Questions