cnak2
cnak2

Reputation: 1841

Getting "error": "Unknown authentication strategy \"jwt\""

I'm implementing an authorization feature using Express, Mongoose, Passport and JWT.

I'm able to register a user ok. I'm able to authenticate and generate a JWT, which I can parse on the JWT site, but for some reason, I'm getting an Unknown authentication strategy error message.

I have all my code blocks laid out on a Plunker instance at:

https://plnkr.co/edit/ZNjQwcZ4rMymzBXNy5nX?p=catalogue

Here is my passport.js file, which contains my strategy:

var JwtStrategy = require('passport-jwt').Strategy;

// load up the user model
var User = require('../models/user');
var config = require('../config/database'); // get db config file

module.exports = function(passport) {
  var opts = {};
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, 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);
          }
      });
  }));
};

Here is what my authentication.js file looks like:

var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database'); 

var User = require('../models/user');



router.route('/')
.post(function(req, res) {

  User.findOne({
    name: req.body.name
  }, function(err, user) {
    if (err)
      res.send(err);

    if (!user) {
      res.send({success: false, msg: 'Authentication failed. User not found.'});
    } else {
      // check if password matches
      user.comparePassword(req.body.password, function (err, isMatch) {
        if (isMatch && !err) {
          // if user is found and password is right create a token
          var token = jwt.encode(user, config.secret);
          // return the information including token as JSON
          res.json({success: true, token: 'JWT ' + token});
        } else {
          res.send({success: false, msg: 'Authentication failed. Wrong password.'});
        }
      });
    }
  });
});


module.exports = router;

Here is the endpoint I'm calling that is generating the error:

var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database'); 
var passport  = require('passport');

var User = require('../models/user');

router.route('/')

.get(passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
  if (token) {
    var decoded = jwt.decode(token, config.secret);
    User.findOne({
      name: decoded.name
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
          return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
        } else {
          res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
        }
    });
  } else {
    return res.status(403).send({success: false, msg: 'No token provided.'});
  }
});

getToken = function (headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
      return parted[1];
    } else {
      return null;
    }
  } else {
    return null;
  }
};

module.exports = router;

Upvotes: 12

Views: 47447

Answers (3)

Sam
Sam

Reputation: 1

Just on the off chance that someone is having the same issue but it isn't resolved by the top answer.

My issue ended up being accidently moving node modules into another directory and then of course running npm install to fix module import errors. I ended up with two node_modules directory and although the server started fine, passport errored when it was called.

I eventually found the blunder and removed the second node_modules directory and the Unknown authentication strategy “jwt” was no resolved.

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80647

You forgot to include your own passport.js module in the application. This leads nodejs to not find the definition of JWTStrategy which is ultimately causing the error that you see.

In your endpoint file, just include the local passport.js file:

var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database'); 
var passport  = require('passport');

require('./passport')(passport) // as strategy in ./passport.js needs passport object

var User = require('../models/user');

router.route('/')
.get(passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
...

Upvotes: 28

Basheer AL-MOMANI
Basheer AL-MOMANI

Reputation: 15357

if you look at your passport configuration file (passport.js) you will see

module.exports = function (passport) {
    //bla bla bla 
} 

as you see it needs passport instance

now how to pass this instance to your passport.js file

simply

var passport = require('passport');// create a passport instance
var myPassportService = require('../config/passport')(passport);// pass it into passport.js file

hope this helps you

Upvotes: 1

Related Questions