Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 544
cnak2 Avatar asked Nov 18 '16 05:11

cnak2


2 Answers

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);
...
like image 139
hjpotter92 Avatar answered Oct 11 '22 11:10

hjpotter92


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

like image 28
Basheer AL-MOMANI Avatar answered Oct 11 '22 10:10

Basheer AL-MOMANI