JSONWebTokens with express jwt VS passport-jwt

The express-jwt package provides tremendous flexibility in creating multiple authentication parameters at login (for example, in local repositories or in social networks OAuth or OpenID providers, etc.), and then protect the application using JWT.

Express jwt configuration, in particular ie

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

shows a way.

Question: Many of the sites that I want to use for login alternatives are most easily accessible through passport.js. Passport-jwt seems to use the jsonwebtokens.js module under the hood, so is there a way to configure passport-jwt with the same flexibility that can be obtained using jsonwebtokens.js and express-jwt.js separately?

+5
source share
1 answer

Yes there is. The passport has many configurations that it denotes strategies. One of them is passport-jwt: https://github.com/themikenicholson/passport-jwt

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

Here is an example with the intended configuration of a regular express application.

 // 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 more flexibility, such as express-jwt, if not more, and can be easily abstracted from your main code.

+2
source

All Articles