Home:ALL Converter>create a custom passport-jwt strategy middleware callback

create a custom passport-jwt strategy middleware callback

Ask Time:2017-04-08T19:48:11         Author:Abderrahman Hilali

Json Formatter

I want to create a custom middleware for passport-jwt to handle authentication.

here is what I have done to create my own middleware :

var models  = require('../models');
var passport = require("passport");  
var passportJWT = require("passport-jwt");  
var config = require("../config/config.json");  
var ExtractJwt = passportJWT.ExtractJwt;  
var Strategy = passportJWT.Strategy;  
var params = {  
    secretOrKey: config.jwtSecret,
    jwtFromRequest: ExtractJwt.fromAuthHeader()
};

/**
 * jwt authentication strategy
 */
var strategy = new Strategy(params, function(payload, done) {
    models.User.findById(payload.id)
    .then((user)=>{
        if (user) {
            return done(null, {
                id: user.id,
                username : user.username
            });
        } else {
            return done(new Error("User not found"), false);
        }
    }).catch((err)=>{
        return done(err, false);
    });
});
passport.use(strategy);

module.exports =  {  
    initialize: function() {
        return passport.initialize();
    },
    authenticate: (req, res, next)=>{
        passport.authenticate('jwt', { session: false }, (err, user, info)=>{ 
            if (err) { return next(err); } 
            if (!user) { return res.send("Custom Unauthorised").end(); } 
            // edit as per comment
            //return res.send("Test Route Accessed").end();
            req.user = user;   // Forward user information to the next middleware
            next();
        })(req, res, next);
    }
};

but everytime I type 'npm start' to run the app I face this error :

if (request.headers[AUTH_HEADER]) { ^ TypeError: Cannot read property 'headers' of undefined.

the authorization header is set in the request.

Author:Abderrahman Hilali,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/43293707/create-a-custom-passport-jwt-strategy-middleware-callback
yy